Software enabled and disabled coalescing of memory transactions

ABSTRACT

A program controls coalescing of outermost memory transactions, the coalescing causing committing of memory store data to memory for a first transaction to be done at transaction execution (TX) end of a second transaction. wherein optimized machine instructions are generated based on an intermediate representation of a program, wherein either two atomic tasks are merged into a single coalesced transaction or are executed as separate transactions.

BACKGROUND OF THE INVENTION

This disclosure relates generally to the field of Transactional Memory(TM) execution, and more specifically to the modification of code tooptimize the processing of multiple memory transactions as a singletransaction.

The number of central processing unit (CPU) cores on a chip and thenumber of CPU cores connected to a shared memory continues to growsignificantly to support growing workload capacity demand. Theincreasing number of CPUs cooperating to process the same workloads putsa significant burden on software scalability; for example, shared queuesor data-structures protected by traditional semaphores become hot spotsand lead to sub-linear n-way scaling curves. Traditionally this has beencountered by implementing finer-grained locking in software, and withlower latency/higher bandwidth interconnects in hardware. Implementingfine-grained locking to improve software scalability can be verycomplicated and error-prone, and at today's CPU frequencies, thelatencies of hardware interconnects are limited by the physicaldimension of the chips and systems, and by the speed of light.

Implementations of hardware Transactional Memory (HTM, or in thisdiscussion, simply TM) have been introduced, wherein a group ofinstructions—called a transaction—operate in an atomic manner on a datastructure in memory, as viewed by other central processing units (CPUs)and the I/O subsystem (atomic operation is also known as “blockconcurrent” or “serialized” in other literature). The transactionexecutes optimistically without obtaining a lock, but may need to abortand retry the transaction execution if an operation, of the executingtransaction, on a memory location conflicts with another operation onthe same memory location. Previously, software transactional memoryimplementations have been proposed to support software TransactionalMemory (TM). However, hardware TM can provide improved performanceaspects and ease of use over software TM.

US Patent Applicatin No. 2007/0162520A1, filed Jul. 12, 2007 “Softwareassisted nested hardware transactions” incorporated by reference hereinteaches a method and apparatus for efficiently executing nestedtransactions. Hardware support for execution of transactions isprovided. Additionally, through the use of logging previous valuesimmediately before a current nested transaction in a local memory andstorage of a stack of handlers associated with a hierarchy oftransactions, nested transactions are potentially efficiently executed.Upon a failure, abort, or invalidating event/access within a nestedtransaction, the state of variables or memory locations written toduring execution of the nested transaction are rolled-back toimmediately before the nested transaction, instead of all the way backto an original state of the variables or memory locations before anenclosing transaction. As a result, nested transactions may bere-executed within enclosing transactions, without flattening theenclosing and nested transactions to re-execute everything.

US Patent Application No. 2010/0205408A1, filed Aug. 12, 2010“Speculative Region: Hardware Support for Selective Transactional MemoryAccess Annotation Using Instruction Prefix” incorporated by referenceherein teaches a computer system and method for executing selectivelyannotated transactional regions. The system is configured to determinewhether an instruction within a plurality of instructions in atransactional region includes a given prefix. The prefix indicates thatone or more memory operations performed by the processor to complete theinstruction are to be executed as part of an atomic transaction. Theatomic transaction can include one or more other memory operationsperformed by the processor to complete one or more others of theplurality of instructions in the transactional region.

Techniques are provided for performing operations in an electronic filesystem as nested transactions. According to one aspect of the invention,a command to perform one or more file system operations is received. Inresponse to the command, a plurality of operations, including the one ormore file system operations, are performed. Performing the plurality ofoperations includes: (1) performing a first subset of the plurality ofoperations as part of a first transaction; and (2) performing a secondsubset of the plurality of operations as part of a second transactionthat is nested in the first transaction.

A method and apparatus for efficiently executing nested transactions isherein described. Hardware support for execution of transactions isprovided. Additionally, through the use of logging previous valuesimmediately before a current nested transaction in a local memory andstorage of a stack of handlers associated with a hierarchy oftransactions, nested transactions are potentially efficiently executed.Upon a failure, abort, or invalidating event/access within a nestedtransaction, the state of variables or memory locations written toduring execution of the nested transaction are rolled-back toimmediately before the nested transaction, instead of all the way backto an original state of the variables or memory locations before anenclosing transaction. As a result, nested transactions may bere-executed within enclosing transactions, without flattening theenclosing and nested transactions to re-execute everything.

SUMMARY

Embodiments of the present disclosure provide a method, computer system,and computer program product for a transactional memory system thatcontrols the coalescing of outermost memory transactions. The coalescingcausing committing of memory store data to memory for a firsttransaction to be done at transaction execution (TX) end of a secondtransaction. A processor of the transactional memory system executes arun-time instrumentation program for monitoring and modifying anassociated program having a plurality of transactions. The processorinitiates execution of the associated program. Based on execution oftransactions, by the processor, of the associated program, the run-timeinstrumentation program dynamically obtains instrumentation informationassociated with the execution. Based on the obtained instrumentationinformation, the processor dynamically modifies continued execution oftransactions of the associated program to optimize transactionalexecution (TX).

BRIEF DESCRIPTION OF THE SEVERAL VIEWS OF THE DRAWINGS

One or more aspects of the present disclosed embodiments areparticularly pointed out and distinctly claimed as examples in theclaims at the conclusion of the specification. The foregoing and otherobjects, features, and advantages of the disclosed embodiments areapparent from the following detailed description taken in conjunctionwith the accompanying drawings in which:

FIGS. 1 and 2 depict block diagrams of an example multi-coreTransactional Memory environment, in accordance with embodiments of thepresent disclosure;

FIG. 3 depicts a block diagram including example components of anexample CPU, in accordance with embodiments of the present disclosure;

FIG. 4 illustrates the operational activity executed by a coalescingcontrol that controls the coalescing of one outmost transaction withanother, in accordance with an embodiment of

FIG. 5 illustrates operational activity executed for the coalescing ofoutermost transactions, in accordance with an embodiment of the presentdisclosure;

FIG. 6 illustrates the operational activity executed by a dynamicprediction that uses transaction history and flags to direct futurecoalescing activity, in accordance with an embodiment of the presentdisclosure;

FIG. 7 illustrates the operational activity executed by a controlindicator that identifies and handles indicators that controltransaction coalescing activity, in accordance with an embodiment of thepresent disclosure;

FIG. 8 illustrates the operational activity executed by a coalescingoptimizer that optimizes coalescing of outermost transactions tomaximize performance gains, in accordance with an embodiment of thepresent disclosure;

FIG. 9 depicts example components of a Java® Run-time Environment (JRE)that supports the execution of a coalescing optimizer, in accordancewith embodiments of the present disclosure;

FIG. 10 depicts a block diagram of components of a computing device thatis executing a coalescing control, a dynamic prediction, a controlindicator and a coalescing optimizer, as well as any software aspects ofoperational activity executed for the coalescing of outermosttransactions, in accordance with embodiments of the present disclosure;

FIG. 11 depicts various hardware structures that exist as part ofprocessor(s), of FIG. 10, in accordance with various embodiments of thepresent disclosure.

FIG. 12 depicts an example of transaction nesting to aid the reader inthe identifying the differences between nested transactions andcoalescing outermost transactions, in accordance with embodiments of thepresent disclosure.

FIG. 13 illustrates a method of operational activity executed by adynamic compiler that performs aspects of the transaction coalescingprocess, in accordance with embodiments of the present disclosure.

FIG. 14 depicts a flow diagram illustrating an embodiment forcontrolling the coalescing of outermost memory transactions, inaccordance with embodiments of the present disclosure; and

FIGS. 15-29 depicts a flow diagram illustrating example embodiments.

DETAILED DESCRIPTION

Historically, a computer system or processor had only a single processor(aka processing unit or central processing unit). The processor includedan instruction processing unit (IPU), a branch unit, a memory controlunit and the like. Such processors were capable of executing a singlethread of a program at a time. Operating systems were developed thatcould time-share a processor by dispatching a program to be executed onthe processor for a period of time, and then dispatching another programto be executed on the processor for another period of time. Astechnology evolved, memory subsystem caches were often added to theprocessor as well as complex dynamic address translation includingtranslation lookaside buffers (TLBs). The IPU itself was often referredto as a processor. As technology continued to evolve, an entireprocessor, could be packaged in a single semiconductor chip or die, sucha processor was referred to as a microprocessor. Then processors weredeveloped that incorporated multiple IPUs, such processors were oftenreferred to as multi-processors. Each such processor of amulti-processor computer system (processor) may include individual orshared caches, memory interfaces, system bus, address translationmechanism and the like. Virtual machine and instruction set architecture(ISA) emulators added a layer of software to a processor, that providedthe virtual machine with multiple “virtual processors” (aka processors)by time-slice usage of a single IPU in a single hardware processor. Astechnology further evolved, multi-threaded processors were developed,enabling a single hardware processor having a single multi-thread IPU toprovide a capability of simultaneously executing threads of differentprograms, thus each thread of a multi-threaded processor appeared to theoperating system as a processor. As technology further evolved, it waspossible to put multiple processors (each having an IPU) on a singlesemiconductor chip or die. These processors were referred to processorcores or just cores. Thus the terms such as processor, centralprocessing unit, processing unit, microprocessor, core, processor core,processor thread, and thread, for example, are often usedinterchangeably. Aspects of embodiments herein may be practiced by anyor all processors including those shown supra, without departing fromthe teachings herein. Wherein the term “thread” or “processor thread” isused herein, it is expected that particular advantage of the embodimentmay be had in a processor thread implementation.

Transaction Execution in Intel® Based Embodiments

In “Intel® Architecture Instruction Set Extensions ProgrammingReference” 319433-012A, February 2012, incorporated herein by referencein its entirety, Chapter 8 teaches, in part, that multithreadedapplications may take advantage of increasing numbers of CPU cores toachieve higher performance. However, the writing of multi-threadedapplications requires programmers to understand and take into accountdata sharing among the multiple threads. Access to shared data typicallyrequires synchronization mechanisms. These synchronization mechanismsare used to ensure that multiple threads update shared data byserializing operations that are applied to the shared data, oftenthrough the use of a critical section that is protected by a lock. Sinceserialization limits concurrency, programmers try to limit the overheaddue to synchronization.

Intel® Transactional Synchronization Extensions (Intel® TSX) allow aprocessor to dynamically determine whether threads need to be serializedthrough lock-protected critical sections, and to perform thatserialization only when required. This allows the processor to exposeand exploit concurrency that is hidden in an application because ofdynamically unnecessary synchronization.

With Intel TSX, programmer-specified code regions (also referred to as“transactional regions” or just “transactions”) are executedtransactionally. If the transactional execution completes successfully,then all memory operations performed within the transactional regionwill appear to have occurred instantaneously when viewed from otherprocessors. A processor makes the memory operations of the executedtransaction, performed within the transactional region, visible to otherprocessors only when a successful commit occurs, i.e., when thetransaction successfully completes execution. This process is oftenreferred to as an atomic commit.

Intel TSX provides two software interfaces to specify regions of codefor transactional execution. Hardware Lock Elision (HLE) is a legacycompatible instruction set extension (comprising the XACQUIRE andXRELEASE prefixes) to specify transactional regions. RestrictedTransactional Memory (RTM) is a new instruction set interface(comprising the XBEGIN, XEND, and XABORT instructions) for programmersto define transactional regions in a more flexible manner than thatpossible with HLE. HLE is for programmers who prefer the backwardcompatibility of the conventional mutual exclusion programming model andwould like to run HLE-enabled software on legacy hardware but would alsolike to take advantage of the new lock elision capabilities on hardwarewith HLE support. RTM is for programmers who prefer a flexible interfaceto the transactional execution hardware. In addition, Intel TSX alsoprovides an XTEST instruction. This instruction allows software to querywhether the logical processor is transactionally executing in atransactional region identified by either HLE or RTM.

Since a successful transactional execution ensures an atomic commit, theprocessor executes the code region optimistically without explicitsynchronization. If synchronization was unnecessary for that specificexecution, execution can commit without any cross-thread serialization.If the processor cannot commit atomically, then the optimistic executionfails. When this happens, the processor will roll back the execution, aprocess referred to as a transactional abort. On a transactional abort,the processor will discard all updates performed in the memory regionused by the transaction, restore architectural state to appear as if theoptimistic execution never occurred, and resume executionnon-transactionally.

A processor can perform a transactional abort for numerous reasons. Aprimary reason to abort a transaction is due to conflicting memoryaccesses between the transactionally executing logical processor andanother logical processor. Such conflicting memory accesses may preventa successful transactional execution. Memory addresses read from withina transactional region constitute the read-set of the transactionalregion and addresses written to within the transactional regionconstitute the write-set of the transactional region. Intel TSXmaintains the read- and write-sets at the granularity of a cache line. Aconflicting memory access occurs if another logical processor eitherreads a location that is part of the transactional region's write-set orwrites a location that is a part of either the read- or write-set of thetransactional region. A conflicting access typically means thatserialization is required for this code region. Since Intel TSX detectsdata conflicts at the granularity of a cache line, unrelated datalocations placed in the same cache line will be detected as conflictsthat result in transactional aborts. Transactional aborts may also occurdue to limited transactional resources. For example, the amount of dataaccessed in the region may exceed an implementation-specific capacity.Additionally, some instructions and system events may causetransactional aborts. Frequent transactional aborts result in wastedcycles and increased inefficiency.

Hardware Lock Elision

Hardware Lock Elision (HLE) provides a legacy compatible instruction setinterface for programmers to use transactional execution. HLE providestwo new instruction prefix hints: XACQUIRE and XRELEASE.

With HLE, a programmer adds the XACQUIRE prefix to the front of theinstruction that is used to acquire the lock that is protecting thecritical section. The processor treats the prefix as a hint to elide thewrite associated with the lock acquire operation. Even though the lockacquire has an associated write operation to the lock, the processordoes not add the address of the lock to the transactional region'swrite-set nor does it issue any write requests to the lock. Instead, theaddress of the lock is added to the read-set. The logical processorenters transactional execution. If the lock was available before theXACQUIRE prefixed instruction, then all other processors will continueto see the lock as available afterwards. Since the transactionallyexecuting logical processor neither added the address of the lock to itswrite-set nor performed externally visible write operations to the lock,other logical processors can read the lock without causing a dataconflict. This allows other logical processors to also enter andconcurrently execute the critical section protected by the lock. Theprocessor automatically detects any data conflicts that occur during thetransactional execution and will perform a transactional abort ifnecessary.

Even though the eliding processor did not perform any external writeoperations to the lock, the hardware ensures program order of operationson the lock. If the eliding processor itself reads the value of the lockin the critical section, it will appear as if the processor had acquiredthe lock, i.e. the read will return the non-elided value. This behaviorallows an HLE execution to be functionally equivalent to an executionwithout the HLE prefixes.

An XRELEASE prefix can be added in front of an instruction that is usedto release the lock protecting a critical section. Releasing the lockinvolves a write to the lock. If the instruction is to restore the valueof the lock to the value the lock had prior to the XACQUIRE prefixedlock acquire operation on the same lock, then the processor elides theexternal write request associated with the release of the lock and doesnot add the address of the lock to the write-set. The processor thenattempts to commit the transactional execution.

With HLE, if multiple threads execute critical sections protected by thesame lock but they do not perform any conflicting operations on eachother's data, then the threads can execute concurrently and withoutserialization. Even though the software uses lock acquisition operationson a common lock, the hardware recognizes this, elides the lock, andexecutes the critical sections on the two threads without requiring anycommunication through the lock—if such communication was dynamicallyunnecessary.

If the processor is unable to execute the region transactionally, thenthe processor will execute the region non-transactionally and withoutelision. HLE enabled software has the same forward progress guaranteesas the underlying non-HLE lock-based execution. For successful HLEexecution, the lock and the critical section code must follow certainguidelines. These guidelines only affect performance; and failure tofollow these guidelines will not result in a functional failure.Hardware without HLE support will ignore the XACQUIRE and XRELEASEprefix hints and will not perform any elision since these prefixescorrespond to the REPNE/REPE IA-32 prefixes which are ignored on theinstructions where XACQUIRE and XRELEASE are valid. Importantly, HLE iscompatible with the existing lock-based programming model. Improper useof hints will not cause functional bugs though it may expose latent bugsalready in the code.

Restricted Transactional Memory (RTM) provides a flexible softwareinterface for transactional execution. RTM provides three newinstructions—XBEGIN, XEND, and XABORT—for programmers to start, commit,and abort a transactional execution.

The programmer uses the XBEGIN instruction to specify the start of atransactional code region and the XEND instruction to specify the end ofthe transactional code region. If the RTM region could not besuccessfully executed transactionally, then the XBEGIN instruction takesan operand that provides a relative offset to the fallback instructionaddress.

A processor may abort RTM transactional execution for many reasons. Inmany instances, the hardware automatically detects transactional abortconditions and restarts execution from the fallback instruction addresswith the architectural state corresponding to that present at the startof the XBEGIN instruction and the EAX register updated to describe theabort status.

The XABORT instruction allows programmers to abort the execution of anRTM region explicitly. The XABORT instruction takes an 8-bit immediateargument that is loaded into the EAX register and will thus be availableto software following an RTM abort. RTM instructions do not have anydata memory location associated with them. While the hardware providesno guarantees as to whether an RTM region will ever successfully committransactionally, most transactions that follow the recommendedguidelines are expected to successfully commit transactionally. However,programmers must always provide an alternative code sequence in thefallback path to guarantee forward progress. This may be as simple asacquiring a lock and executing the specified code regionnon-transactionally. Further, a transaction that always aborts on agiven implementation may complete transactionally on a futureimplementation. Therefore, programmers must ensure the code paths forthe transactional region and the alternative code sequence arefunctionally tested.

Detection of HLE Support

A processor supports HLE execution if CPUID.07H.EBX.HLE [bit 4]=1.However, an application can use the HLE prefixes (XACQUIRE and XRELEASE)without checking whether the processor supports HLE. Processors withoutHLE support ignore these prefixes and will execute the code withoutentering transactional execution.

Detection of RTM Support

A processor supports RTM execution if CPUID.07H.EBX.RTM [bit 11]=1. Anapplication must check if the processor supports RTM before it uses theRTM instructions (XBEGIN, XEND, XABORT). These instructions willgenerate a #UD exception when used on a processor that does not supportRTM.

Detection of XTEST Instruction

A processor supports the XTEST instruction if it supports either HLE orRTM. An application must check either of these feature flags beforeusing the XTEST instruction. This instruction will generate a #UDexception when used on a processor that does not support either HLE orRTM.

Querying Transactional Execution Status

The XTEST instruction can be used to determine the transactional statusof a transactional region specified by HLE or RTM. Note, while the HLEprefixes are ignored on processors that do not support HLE, the XTESTinstruction will generate a #UD exception when used on processors thatdo not support either HLE or RTM.

Requirements for HLE Locks

For HLE execution to successfully commit transactionally, the lock mustsatisfy certain properties and access to the lock must follow certainguidelines.

An XRELEASE prefixed instruction must restore the value of the elidedlock to the value it had before the lock acquisition. This allowshardware to safely elide locks by not adding them to the write-set. Thedata size and data address of the lock release (XRELEASE prefixed)instruction must match that of the lock acquire (XACQUIRE prefixed) andthe lock must not cross a cache line boundary.

Software should not write to the elided lock inside a transactional HLEregion with any instruction other than an XRELEASE prefixed instruction,otherwise such a write may cause a transactional abort. In addition,recursive locks (where a thread acquires the same lock multiple timeswithout first releasing the lock) may also cause a transactional abort.Note that software can observe the result of the elided lock acquireinside the critical section. Such a read operation will return the valueof the write to the lock.

The processor automatically detects violations to these guidelines, andsafely transitions to a non-transactional execution without elision.Since Intel TSX detects conflicts at the granularity of a cache line,writes to data collocated on the same cache line as the elided lock maybe detected as data conflicts by other logical processors eliding thesame lock.

Transactional Nesting

Both HLE and RTM support nested transactional regions. However, atransactional abort restores state to the operation that startedtransactional execution: either the outermost XACQUIRE prefixed HLEeligible instruction or the outermost XBEGIN instruction. The processortreats all nested transactions as one transaction.

HLE Nesting and Elision

Programmers can nest HLE regions up to an implementation specific depthof MAX_HLE_NEST_COUNT. Each logical processor tracks the nesting countinternally but this count is not available to software. An XACQUIREprefixed HLE-eligible instruction increments the nesting count, and anXRELEASE prefixed HLE-eligible instruction decrements it. The logicalprocessor enters transactional execution when the nesting count goesfrom zero to one. The logical processor attempts to commit only when thenesting count becomes zero. A transactional abort may occur if thenesting count exceeds MAX_HLE_NEST_COUNT.

In addition to supporting nested HLE regions, the processor can alsoelide multiple nested locks. The processor tracks a lock for elisionbeginning with the XACQUIRE prefixed HLE eligible instruction for thatlock and ending with the XRELEASE prefixed HLE eligible instruction forthat same lock. The processor can, at any one time, track up to aMAX_HLE_ELIDED_LOCKS number of locks. For example, if the implementationsupports a MAX_HLE_ELIDED_LOCKS value of two and if the programmer neststhree HLE identified critical sections (by performing XACQUIRE prefixedHLE eligible instructions on three distinct locks without performing anintervening XRELEASE prefixed HLE eligible instruction on any one of thelocks), then the first two locks will be elided, but the third won't beelided (but will be added to the transaction's writeset). However, theexecution will still continue transactionally. Once an XRELEASE for oneof the two elided locks is encountered, a subsequent lock acquiredthrough the XACQUIRE prefixed HLE eligible instruction will be elided.

The processor attempts to commit the HLE execution when all elidedXACQUIRE and XRELEASE pairs have been matched, the nesting count goes tozero, and the locks have satisfied requirements. If execution cannotcommit atomically, then execution transitions to a non-transactionalexecution without elision as if the first instruction did not have anXACQUIRE prefix.

RTM Nesting

Programmers can nest RTM regions up to an implementation specificMAX_RTM_NEST_COUNT. The logical processor tracks the nesting countinternally but this count is not available to software. An XBEGINinstruction increments the nesting count, and an XEND instructiondecrements the nesting count. The logical processor attempts to commitonly if the nesting count becomes zero. A transactional abort occurs ifthe nesting count exceeds MAX_RTM_NEST_COUNT.

Nesting HLE and RTM

HLE and RTM provide two alternative software interfaces to a commontransactional execution capability. Transactional processing behavior isimplementation specific when HLE and RTM are nested together, e.g., HLEis inside RTM or RTM is inside HLE. However, in all cases, theimplementation will maintain HLE and RTM semantics. An implementationmay choose to ignore HLE hints when used inside RTM regions, and maycause a transactional abort when RTM instructions are used inside HLEregions. In the latter case, the transition from transactional tonon-transactional execution occurs seamlessly since the processor willre-execute the HLE region without actually doing elision, and thenexecute the RTM instructions.

Abort Status Definition

RTM uses the EAX register to communicate abort status to software.Following an RTM abort the EAX register has the following definition.

TABLE 1 RTM Abort Status Definition EAX Register Bit Position Meaning 0Set if abort caused by XABORT instruction 1 If set, the transaction maysucceed on retry, this bit is always clear if bit 0 is set 2 Set ifanother logical processor conflicted with a memory address that was partof the transaction that aborted 3 Set if an internal buffer overflowed 4Set if a debug breakpoint was hit 5 Set if an abort occurred duringexecution of a nested transaction 23:6 Reserved 31-24 XABORT argument(only valid if bit 0 set, otherwise reserved)

The EAX abort status for RTM only provides causes for aborts. It doesnot by itself encode whether an abort or commit occurred for the RTMregion. The value of EAX can be 0 following an RTM abort. For example, aCPUID instruction when used inside an RTM region causes a transactionalabort and may not satisfy the requirements for setting any of the EAXbits. This may result in an EAX value of 0.

RTM Memory Ordering

A successful RTM commit causes all memory operations in the RTM regionto appear to execute atomically. A successfully committed RTM regionconsisting of an XBEGIN followed by an XEND, even with no memoryoperations in the RTM region, has the same ordering semantics as a LOCKprefixed instruction.

The XBEGIN instruction does not have fencing semantics. However, if anRTM execution aborts, then all memory updates from within the RTM regionare discarded and are not made visible to any other logical processor.

RTM-Enabled Debugger Support

By default, any debug exception inside an RTM region will cause atransactional abort and will redirect control flow to the fallbackinstruction address with architectural state recovered and bit 4 in EAXset. However, to allow software debuggers to intercept execution ondebug exceptions, the RTM architecture provides additional capability.

If bit 11 of DR7 and bit 15 of the IA32_DEBUGCTL_MSR are both 1, any RTMabort due to a debug exception (#DB) or breakpoint exception (#BP)causes execution to roll back and restart from the XBEGIN instructioninstead of the fallback address. In this scenario, the EAX register willalso be restored back to the point of the XBEGIN instruction.

Programming Considerations

Typical programmer-identified regions are expected to transactionallyexecute and commit successfully. However, Intel TSX does not provide anysuch guarantee. A transactional execution may abort for many reasons. Totake full advantage of the transactional capabilities, programmersshould follow certain guidelines to increase the probability of theirtransactional execution committing successfully.

This section discusses various events that may cause transactionalaborts. The architecture ensures that updates performed within atransaction that subsequently aborts execution will never becomevisible. Only committed transactional executions initiate an update tothe architectural state. Transactional aborts never cause functionalfailures and only affect performance.

Instruction Based Considerations

Programmers can use any instruction safely inside a transaction (HLE orRTM) and can use transactions at any privilege level. However, someinstructions will always abort the transactional execution and causeexecution to seamlessly and safely transition to a non-transactionalpath.

Intel TSX allows for most common instructions to be used insidetransactions without causing aborts. The following operations inside atransaction do not typically cause an abort:

-   -   Operations on the instruction pointer register, general purpose        registers (GPRs) and the status flags (CF, OF, SF, PF, AF, and        ZF); and    -   Operations on XMM and YMM registers and the MXCSR register.

However, programmers must be careful when intermixing SSE and AVXoperations inside a transactional region. Intermixing SSE instructionsaccessing XMM registers and AVX instructions accessing YMM registers maycause transactions to abort. Programmers may use REP/REPNE prefixedstring operations inside transactions. However, long strings may causeaborts. Further, the use of CLD and STD instructions may cause aborts ifthey change the value of the DF flag. However, if DF is 1, the STDinstruction will not cause an abort. Similarly, if DF is 0, then the CLDinstruction will not cause an abort.

Instructions not enumerated here as causing abort when used inside atransaction will typically not cause a transaction to abort (examplesinclude but are not limited to MFENCE, LFENCE, SFENCE, RDTSC, RDTSCP,etc.).

The following instructions will abort transactional execution on anyimplementation:

-   -   XABORT    -   CPUID    -   PAUSE

In addition, in some implementations, the following instructions mayalways cause transactional aborts. These instructions are not expectedto be commonly used inside typical transactional regions. However,programmers must not rely on these instructions to force a transactionalabort, since whether they cause transactional aborts is implementationdependent.

-   -   Operations on X87 and MMX architecture state. This includes all        MMX and X87 instructions, including the FXRSTOR and FXSAVE        instructions.    -   Update to non-status portion of EFLAGS: CLI, STI, POPFD, POPFQ,        CLTS.    -   Instructions that update segment registers, debug registers        and/or control registers: MOV to DS/ES/FS/GS/SS, POP        DS/ES/FS/GS/SS, LDS, LES, LFS, LGS, LSS, SWAPGS, WRFSBASE,        WRGSBASE, LGDT, SGDT, LIDT, SIDT, LLDT, SLDT, LTR, STR, Far        CALL, Far JMP, Far RET, IRET, MOV to DRx, MOV to        CR0/CR2/CR3/CR4/CR8 and LMSW.    -   Ring transitions: SYSENTER, SYSCALL, SYSEXIT, and SYSRET.    -   TLB and Cacheability control: CLFLUSH, INVD, WBINVD, INVLPG,        INVPCID, and memory instructions with a non-temporal hint        (MOVNTDQA, MOVNTDQ, MOVNTI, MOVNTPD, MOVNTPS, and MOVNTQ).    -   Processor state save: XSAVE, XSAVEOPT, and XRSTOR.    -   Interrupts: INTn, INTO.    -   IO: IN, INS, REP INS, OUT, OUTS, REP OUTS and their variants.    -   VMX: VMPTRLD, VMPTRST, VMCLEAR, VMREAD, VMWRITE, VMCALL,        VMLAUNCH, VMRESUME, VMXOFF, VMXON, INVEPT, and INVVPID.    -   SMX: GETSEC.    -   UD2, RSM, RDMSR, WRMSR, HLT, MONITOR, MWAIT, XSETBV, VZEROUPPER,        MASKMOVQ, and V/MASKMOVDQU.

Runtime Considerations

In addition to the instruction-based considerations, runtime events maycause transactional execution to abort. These may be due to data accesspatterns or micro-architectural implementation features. The followinglist is not a comprehensive discussion of all abort causes.

Any fault or trap in a transaction that must be exposed to software willbe suppressed. Transactional execution will abort and execution willtransition to a non-transactional execution, as if the fault or trap hadnever occurred. If an exception is not masked, then that un-maskedexception will result in a transactional abort and the state will appearas if the exception had never occurred.

Synchronous exception events (#DE, #OF, #NP, #SS, #GP, #BR, #UD, #AC,#XF, #PF, #NM, #TS, #MF, #DB, #BP/INT3) that occur during transactionalexecution may cause an execution not to commit transactionally, andrequire a non-transactional execution. These events are suppressed as ifthey had never occurred. With HLE, since the non-transactional code pathis identical to the transactional code path, these events will typicallyre-appear when the instruction that caused the exception is re-executednon-transactionally, causing the associated synchronous events to bedelivered appropriately in the non-transactional execution. Asynchronousevents (NMI, SMI, INTR, IPI, PMI, etc.) occurring during transactionalexecution may cause the transactional execution to abort and transitionto a non-transactional execution. The asynchronous events will be pendedand handled after the transactional abort is processed.

Transactions only support write-back cacheable memory type operations. Atransaction may always abort if the transaction includes operations onany other memory type. This includes instruction fetches to UC memorytype.

Memory accesses within a transactional region may require the processorto set the Accessed and Dirty flags of the referenced page table entry.The behavior of how the processor handles this is implementationspecific. Some implementations may allow the updates to these flags tobecome externally visible even if the transactional region subsequentlyaborts. Some Intel TSX implementations may choose to abort thetransactional execution if these flags need to be updated. Further, aprocessor's page-table walk may generate accesses to its owntransactionally written but uncommitted state. Some Intel TSXimplementations may choose to abort the execution of a transactionalregion in such situations. Regardless, the architecture ensures that, ifthe transactional region aborts, then the transactionally written statewill not be made architecturally visible through the behavior ofstructures such as TLBs.

Executing self-modifying code transactionally may also causetransactional aborts. Programmers must continue to follow the Intelrecommended guidelines for writing self-modifying and cross-modifyingcode even when employing HLE and RTM. While an implementation of RTM andHLE will typically provide sufficient resources for executing commontransactional regions, implementation constraints and excessive sizesfor transactional regions may cause a transactional execution to abortand transition to a non-transactional execution. The architectureprovides no guarantee of the amount of resources available to dotransactional execution and does not guarantee that a transactionalexecution will ever succeed.

Conflicting requests to a cache line accessed within a transactionalregion may prevent the transaction from executing successfully. Forexample, if logical processor P0 reads line A in a transactional regionand another logical processor P1 writes line A (either inside or outsidea transactional region) then logical processor P0 may abort if logicalprocessor P1's write interferes with processor P0's ability to executetransactionally.

Similarly, if P0 writes line A in a transactional region and P1 reads orwrites line A (either inside or outside a transactional region), then P0may abort if P1's access to line A interferes with P0's ability toexecute transactionally. In addition, other coherence traffic may attimes appear as conflicting requests and may cause aborts. While thesefalse conflicts may happen, they are expected to be uncommon. Theconflict resolution policy to determine whether P0 or P1 aborts in theabove scenarios is implementation specific.

Generic Transaction Execution Embodiments:

According to “ARCHITECTURES FOR TRANSACTIONAL MEMORY”, a dissertationsubmitted to the Department of Computer Science and the Committee onGraduate Studies of Stanford University in partial fulfillment of therequirements for the Degree of Doctor of Philosophy, by Austen McDonald,June 2009, incorporated by reference herein in its entirety,fundamentally, there are three mechanisms needed to implement an atomicand isolated transactional region: versioning, conflict detection, andcontention management.

To make a transactional code region appear atomic, all the modificationsperformed by that transactional code region must be stored and keptisolated from other transactions until commit time. The system does thisby implementing a versioning policy. Two versioning paradigms exist:eager and lazy. An eager versioning system stores newly generatedtransactional values in place and stores previous memory values on theside, in what is called an undo-log. A lazy versioning system stores newvalues temporarily in what is called a write buffer, copying them tomemory only on commit. In either system, the cache is used to optimizestorage of new versions.

To ensure that transactions appear to be performed atomically, conflictsmust be detected and resolved. The two systems, i.e., the eager and lazyversioning systems, detect conflicts by implementing a conflictdetection policy, either optimistic or pessimistic. An optimistic systemexecutes transactions in parallel, checking for conflicts only when atransaction commits. A pessimistic system checks for conflicts at eachload and store. Similar to versioning, conflict detection also uses thecache, marking each line as either part of the read-set, part of thewrite-set, or both. The two systems resolve conflicts by implementing acontention management policy. Many contention management policies exist,some are more appropriate for optimistic conflict detection and some aremore appropriate for pessimistic. Described below are some examplepolicies.

Since each transactional memory (TM) system needs both versioningdetection and conflict detection, these options give rise to fourdistinct TM designs: Eager-Pessimistic (EP), Eager-Optimistic (EO),Lazy-Pessimistic (LP), and Lazy-Optimistic (LO). Table 2 brieflydescribes all four distinct TM designs.

FIGS. 1 and 2 depict block diagrams of an example multi-coreTransactional Memory environment, in accordance with embodiments of thepresent disclosure. FIG. 1 shows many TM-enabled CPUs (CPU1 114 a, CPU2114 b, etc.) on one die 100, connected with an interconnect 122, undermanagement of an interconnect control 120 a, 120 b. Each CPU 114 a, 114b (also known as a Processor) may have a split cache consisting of anInstruction Cache 116 a, 166 b for caching instructions from memory tobe executed and a Data Cache 118 a, 118 b with TM support for cachingdata (operands) of memory locations to be operated on by CPU 114 a, 114b (in FIG. 1, each CPU 114 a, 114 b and its associated caches arereferenced as 112 a, 112 b). In an implementation, caches of multipledies, such as multiple die 100, are interconnected to support cachecoherency between the caches of multiple instances of die 100. In animplementation, a single cache, rather than the split cache is employedholding both instructions and data. In implementations, the CPU cachesare one level of caching in a hierarchical cache structure. For exampleeach die 100 may employ a shared cache 124 to be shared amongst all theCPUs on the die 100. In another implementation, each die 100 may haveaccess to a common shared cache 124, which is shared amongst all theprocessors of the multiple instances of die 100.

FIG. 2 shows the details of an example transactional CPU environment112, having a CPU 114, including additions to support TM. TransactionalCPU (processor) 114 may include hardware for supporting RegisterCheckpoints 126 and special TM Registers 128. The transactional CPUcache may have the MESI bits 130, Tags 140 and Data 142 of aconventional cache but also, for example, R bits 132 showing a line hasbeen read by CPU 114 while executing a transaction and W bits 138showing a line has been written-to by CPU 114 while executing atransaction.

A key detail for programmers in any TM system is how non-transactionalaccesses interact with transactions. By design, transactional accessesare screened from each other using the mechanisms above. However, theinteraction between a regular, non-transactional load with a transactioncontaining a new value for that address must still be considered. Inaddition, the interaction between a non-transactional store with atransaction that has read that address must also be explored. These areissues of the database concept isolation.

A TM system is said to implement strong isolation, sometimes calledstrong atomicity, when every non-transactional load and store acts likean atomic transaction. Therefore, non-transactional loads cannot seeuncommitted data and non-transactional stores cause atomicity violationsin any transactions that have read that address. A system where this isnot the case is said to implement weak isolation, sometimes called weakatomicity.

Strong isolation is often more desirable than weak isolation due to therelative ease of conceptualization and implementation of strongisolation. Additionally, if a programmer has forgotten to surround someshared memory references with transactions, causing bugs, then withstrong isolation, the programmer will often detect that oversight usinga simple debug interface because the programmer will see anon-transactional region causing atomicity violations. Also, programswritten in one model may work differently on another model.

Further, strong isolation is often easier to support in hardware TM thanweak isolation. With strong isolation, since the coherence protocolalready manages load and store communication between processors,transactions can detect non-transactional loads and stores and actappropriately. To implement strong isolation in software TransactionalMemory (TM), non-transactional code must be modified to include read-and write-barriers; potentially crippling performance. Although greateffort has been expended to remove many un-needed barriers, suchtechniques are often complex and performance is typically far lower thanthat of HTMs.

TABLE 2 Transactional Memory Design Space VERSIONING Lazy Eager CONFLICTOpti- Storing updates Not practical: waiting DETECTION mistic in a writeto update memory until buffer; detecting commit time but conflicts atdetecting conflicts at commit time. access time guarantees wasted workand provides no advantage Pessi- Storing updates Updating memory,keeping mistic in a write old values in undo log; buffer; detectingdetecting conflicts at conflicts at access time. access time.

Table 2 illustrates the fundamental design space of transactional memory(versioning and conflict detection).

Eager-Pessimistic (EP)

This first TM design described below is known as Eager-Pessimistic. AnEP system stores its write-set “in place” (hence the name “eager”) and,to support rollback, stores the old values of overwritten lines in an“undo log”. Processors use W 138 and R 132 cache bits to track read andwrite-sets and detect conflicts when receiving snooped load requests.Perhaps the most notable examples of EP systems in known literature areLogTM and UTM.

Beginning a transaction in an EP system is much like beginning atransaction in other systems: tm_begin( ) takes a register checkpoint,and initializes any status registers. An EP system also requiresinitializing the undo log, the details of which are dependent on the logformat, but often involve initializing a log base pointer to a region ofpre-allocated, thread-private memory, and clearing a log boundsregister.

Versioning: In EP, due to the way eager versioning is designed tofunction, MESI 130 state transitions (cache line indicatorscorresponding to Modified, Exclusive, Shared, and Invalid code states)are left mostly unchanged. Outside of a transaction, MESI 130 statetransitions are left completely unchanged. When reading a line inside atransaction, the standard coherence transitions apply (S (Shared)→S, I(Invalid)→S, or I→E (Exclusive)), issuing a load miss as needed, but R132 bit is also set. Likewise, writing a line applies the standardtransitions (S→M, E→I, I→M), issuing a miss as needed, but also sets W138 (Written) bit. The first time a line is written, the old version ofthe entire line is loaded then written to the undo log to preserve it incase the current transaction aborts. The newly written data is thenstored “in-place,” over the old data.

Conflict Detection: Pessimistic conflict detection uses coherencemessages exchanged on misses, or upgrades, to look for conflicts betweentransactions. When a read miss occurs within a transaction, otherprocessors receive a load request; but they ignore the request if theydo not have the needed line. If the other processors have the neededline non-speculatively or have line R 132 (Read), they downgrade thatline to S, and in certain cases issue a cache-to-cache transfer if theyhave the line in MESI's 130 M or E state. However, if the cache has theline W 138, then a conflict is detected between the two transactions andadditional action(s) must be taken.

Similarly, when a transaction seeks to upgrade a line from shared tomodified (on a first write), the transaction issues an exclusive loadrequest, which is also used to detect conflicts. If a receiving cachehas the line non-speculatively, then the line is invalidated, and incertain cases a cache-to-cache transfer (M or E states) is issued. But,if the line is R 132 or W 138, a conflict is detected.

Validation: Because conflict detection is performed on every load, atransaction always has exclusive access to its own write-set. Therefore,validation does not require any additional work.

Commit: Since eager versioning stores the new version of data items inplace, the commit process simply clears W 138 and R 132 bits anddiscards the undo log.

Abort: When a transaction rolls back, the original version of each cacheline in the undo log must be restored, a process called “unrolling” or“applying” the log. This is done during tm_discard( ) and must be atomicwith regard to other transactions. Specifically, the write-set muststill be used to detect conflicts: this transaction has the only correctversion of lines in its undo log, and requesting transactions must waitfor the correct version to be restored from that log. Such a log can beapplied using a hardware state machine or software abort handler.

Eager-Pessimistic has the characteristics of: Commit is simple and sinceit is in-place, very fast. Similarly, validation is a no-op. Pessimisticconflict detection detects conflicts early, thereby reducing the numberof “doomed” transactions. For example, if two transactions are involvedin a Write-After-Read dependency, then that dependency is detectedimmediately in pessimistic conflict detection. However, in optimisticconflict detection such conflicts are not detected until the writercommits.

Eager-Pessimistic also has the characteristics of: As described above,the first time a cache line is written, the old value must be written tothe log, incurring extra cache accesses. Aborts are expensive as theyrequire undoing the log. For each cache line in the log, a load must beissued, perhaps going as far as main memory before continuing to thenext line. Pessimistic conflict detection also prevents certainserializable schedules from existing.

Additionally, because conflicts are handled as they occur, there is apotential for livelock and careful contention management mechanisms mustbe employed to guarantee forward progress.

Lazy-Optimistic (LO)

Another popular TM design is Lazy-Optimistic (LO), which stores itswrite-set in a “write buffer” or “redo log” and detects conflicts atcommit time (still using R 132 and W 138 bits).

Versioning: Just as in the EP system, the MESI protocol of the LO designis enforced outside of the transactions. Once inside a transaction,reading a line incurs the standard MESI transitions but also sets R 132bit. Likewise, writing a line sets W 138 bit of the line, but handlingthe MESI transitions of the LO design is different from that of the EPdesign. First, with lazy versioning, the new versions of written dataare stored in the cache hierarchy until commit while other transactionshave access to old versions available in memory or other caches. To makeavailable the old versions, dirty lines (M lines) must be evicted whenfirst written by a transaction. Second, no upgrade misses are neededbecause of the optimistic conflict detection feature: if a transactionhas a line in the S state, it can simply write to it and upgrade thatline to an M state without communicating the changes with othertransactions because conflict detection is done at commit time.

Conflict Detection and Validation: To validate a transaction and detectconflicts, LO communicates the addresses of speculatively modified linesto other transactions only when it is preparing to commit. Onvalidation, the processor sends one, potentially large, network packetcontaining all the addresses in the write-set. Data is not sent, butleft in the cache of the committer and marked dirty (M). To build thispacket without searching the cache for lines marked W, a simple bitvector is used, called a “store buffer,” with one bit per cache line totrack these speculatively modified lines. Other transactions use thisaddress packet to detect conflicts: if an address is found in the cacheand R 132 and/or W 138 bits are set, then a conflict is initiated. Ifthe line is found but neither R 132 nor W 138 is set, then the line issimply invalidated, which is similar to processing an exclusive load.

To support transaction atomicity, these address packets must be handledatomically, i.e., no two address packets may exist at once with the sameaddresses. In an LO system, this can be achieved by simply acquiring aglobal commit token before sending the address packet. However, atwo-phase commit scheme could be employed by first sending out theaddress packet, collecting responses, enforcing an ordering protocol(perhaps oldest transaction first), and committing once all responsesare satisfactory.

Commit: Once validation has occurred, commit needs no special treatment:simply clear W 138 and R 132 bits and the store buffer. Thetransaction's writes are already marked dirty in the cache and othercaches' copies of these lines have been invalidated via the addresspacket. Other processors can then access the committed data through theregular coherence protocol.

Abort: Rollback is equally easy: because the write-set is containedwithin the local caches, these lines can be invalidated, then clear W138 and R 132 bits and the store buffer. The store buffer allows W linesto be found to invalidate without the need to search the cache.

Lazy-Optimistic has the characteristics of: Aborts are very fast,requiring no additional loads or stores and making only local changes.More serializable schedules can exist than found in EP, which allows anLO system to more aggressively speculate that transactions areindependent, which can yield higher performance. Finally, the latedetection of conflicts can increase the likelihood of forward progress.

Lazy-Optimistic also has the characteristics of: Validation takes globalcommunication time proportional to size of write set. Doomedtransactions can waste work since conflicts are detected only at committime.

Lazy-Pessimistic (LP)

Lazy-Pessimistic (LP) represents a third TM design option, sittingsomewhere between EP and LO: storing newly written lines in a writebuffer but detecting conflicts on a per access basis.

Versioning: Versioning is similar but not identical to that of LO:reading a line sets its R bit 132, writing a line sets its W bit 138,and a store buffer is used to track W lines in the cache. Also, dirty(M) lines must be evicted when first written by a transaction, just asin LO. However, since conflict detection is pessimistic, load exclusivesmust be performed when upgrading a transactional line from I, S→M, whichis unlike LO.

Conflict Detection: LP's conflict detection operates the same as EP's:using coherence messages to look for conflicts between transactions.

Validation: Like in EP, pessimistic conflict detection ensures that atany point, a running transaction has no conflicts with any other runningtransaction, so validation is a no-op.

Commit: Commit needs no special treatment: simply clear W 138 and R 132bits and the store buffer, like in LO.

Abort: Rollback is also like that of LO: simply invalidate the write-setusing the store buffer and clear the W and R bits and the store buffer.

Eager-Optimistic (EO)

The LP has the characteristics of: Like LO, aborts are very fast. LikeEP, the use of pessimistic conflict detection reduces the number of“doomed” transactions Like EP, some serializable schedules are notallowed and conflict detection must be performed on each cache miss.

The final combination of versioning and conflict detection isEager-Optimistic (EO). EO may be a less than optimal choice for HTMsystems: since new transactional versions are written in-place, othertransactions have no choice but to notice conflicts as they occur (i.e.,as cache misses occur). But since EO waits until commit time to detectconflicts, those transactions become “zombies,” continuing to execute,wasting resources, yet are “doomed” to abort.

EO has proven to be useful in STMs and is implemented by Bartok-STM andMcRT. A lazy versioning STM needs to check its write buffer on each readto ensure that it is reading the most recent value. Since the writebuffer is not a hardware structure, this is expensive, hence thepreference for write-in-place eager versioning. Additionally, sincechecking for conflicts is also expensive in an STM, optimistic conflictdetection offers the advantage of performing this operation in bulk.

Contention Management

How a transaction rolls back once the system has decided to abort thattransaction has been described above, but, since a conflict involves twotransactions, the topics of which transaction should abort, how thatabort should be initiated, and when should the aborted transaction beretried need to be explored. These are topics that are addressed byContention Management (CM), a key component of transactional memory.Described below are policies regarding how the systems initiate abortsand the various established methods of managing which transactionsshould abort in a conflict.

Contention Management Policies

A Contention Management (CM) Policy is a mechanism that determines whichtransaction involved in a conflict should abort and when the abortedtransaction should be retried. For example, it is often the case thatretrying an aborted transaction immediately does not lead to the bestperformance. Conversely, employing a back-off mechanism, which delaysthe retrying of an aborted transaction, can yield better performance.STMs first grappled with finding the best contention management policiesand many of the policies outlined below were originally developed forSTMs.

CM Policies draw on a number of measures to make decisions, includingages of the transactions, size of read- and write-sets, the number ofprevious aborts, etc. The combinations of measures to make suchdecisions are endless, but certain combinations are described below,roughly in order of increasing complexity.

To establish some nomenclature, first note that in a conflict there aretwo sides: the attacker and the defender. The attacker is thetransaction requesting access to a shared memory location. Inpessimistic conflict detection, the attacker is the transaction issuingthe load or load exclusive. In optimistic, the attacker is thetransaction attempting to validate. The defender in both cases is thetransaction receiving the attacker's request.

An Aggressive CM Policy immediately and always retries either theattacker or the defender. In LO, Aggressive means that the attackeralways wins, and so Aggressive is sometimes called committer wins. Sucha policy was used for the earliest LO systems. In the case of EP,Aggressive can be either defender wins or attacker wins.

Restarting a conflicting transaction that will immediately experienceanother conflict is bound to waste work—namely interconnect bandwidthrefilling cache misses. A Polite CM Policy employs exponential backoff(but linear could also be used) before restarting conflicts. To preventstarvation, a situation where a process does not have resourcesallocated to it by the scheduler, the exponential backoff greatlyincreases the odds of transaction success after some n retries.

Another approach to conflict resolution is to randomly abort theattacker or defender (a policy called Randomized). Such a policy may becombined with a randomized backoff scheme to avoid unneeded contention.

However, making random choices, when selecting a transaction to abort,can result in aborting transactions that have completed “a lot of work”,which can waste resources. To avoid such waste, the amount of workcompleted on the transaction can be taken into account when determiningwhich transaction to abort. One measure of work could be a transaction'sage. Other methods include Oldest, Bulk TM, Size Matters, Karma, andPolka. Oldest is a simple timestamp method that aborts the youngertransaction in a conflict. Bulk TM uses this scheme. Size Matters islike Oldest but instead of transaction age, the number of read/writtenwords is used as the priority, reverting to Oldest after a fixed numberof aborts. Karma is similar, using the size of the write-set aspriority. Rollback then proceeds after backing off a fixed amount oftime. Aborted transactions keep their priorities after being aborted(hence the name Karma). Polka works like Karma but instead of backingoff a predefined amount of time, it backs off exponentially more eachtime.

Since aborting wastes work, it is logical to argue that stalling anattacker until the defender has finished their transaction would lead tobetter performance. Unfortunately, such a simple scheme easily leads todeadlock.

Deadlock avoidance techniques can be used to solve this problem. Greedyuses two rules to avoid deadlock. The first rule is, if a firsttransaction, T1, has lower priority than a second transaction, T0, or ifT1 is waiting for another transaction, then T1 aborts when conflictingwith T0. The second rule is, if T1 has higher priority than T0 and isnot waiting, then T0 waits until T1 commits, aborts, or starts waiting(in which case the first rule is applied). Greedy provides someguarantees about time bounds for executing a set of transactions. One EPdesign (LogTM) uses a CM policy similar to Greedy to achieve stallingwith conservative deadlock avoidance.

Example MESI coherency rules provide for four possible states in which acache line of a multiprocessor cache system may reside, M, E, S, and I,defined as follows:

Modified (M): The cache line is present only in the current cache, andis dirty; it has been modified from the value in main memory. The cacheis required to write the data back to main memory at some time in thefuture, before permitting any other read of the (no longer valid) mainmemory state. The write-back changes the line to the Exclusive state.

Exclusive (E): The cache line is present only in the current cache, butis clean; it matches main memory. It may be changed to the Shared stateat any time, in response to a read request. Alternatively, it may bechanged to the Modified state when writing to it.

Shared (S): Indicates that this cache line may be stored in other cachesof the machine and is “clean”; it matches the main memory. The line maybe discarded (changed to the Invalid state) at any time.

Invalid (I): Indicates that this cache line is invalid (unused).

TM coherency status indicators (R 132, W 138) may be provided for eachcache line, in addition to, or encoded in the MESI coherency bits. An R132 indicator indicates the current transaction has read from the dataof the cache line, and a W 138 indicator indicates the currenttransaction has written to the data of the cache line.

In another aspect of TM design, a system is designed using transactionalstore buffers. U.S. Pat. No. 6,349,361 titled “Methods and Apparatus forReordering and Renaming Memory References in a Multiprocessor ComputerSystem,” filed Mar. 31, 2000 and incorporated by reference herein in itsentirety, teaches a method for reordering and renaming memory referencesin a multiprocessor computer system having at least a first and a secondprocessor. The first processor has a first private cache and a firstbuffer, and the second processor has a second private cache and a secondbuffer. The method includes the steps of, for each of a plurality ofgated store requests received by the first processor to store a datum,exclusively acquiring a cache line that contains the datum by the firstprivate cache, and storing the datum in the first buffer. Upon the firstbuffer receiving a load request from the first processor to load aparticular datum, the particular datum is provided to the firstprocessor from among the data stored in the first buffer based on anin-order sequence of load and store operations. Upon the first cachereceiving a load request from the second cache for a given datum, anerror condition is indicated and a current state of at least one of theprocessors is reset to an earlier state when the load request for thegiven datum corresponds to the data stored in the first buffer.

The main implementation components of one such transactional memoryfacility are a transaction-backup register file for holdingpre-transaction GR (general register) content, a cache directory totrack the cache lines accessed during the transaction, a store cache tobuffer stores until the transaction ends, and firmware routines toperform various complex functions. In this section a detailedimplementation is described.

IBM zEnterprise EC12 Enterprise Server Embodiment

The IBM zEnterprise EC12 enterprise server introduces transactionalexecution (TX) in transactional memory, and is described in part in apaper, “Transactional Memory Architecture and Implementation for IBMSystem z” of Proceedings Pages 25-36 presented at MICRO-45, 1-5 Dec.2012, Vancouver, British Columbia, Canada, available from IEEE ComputerSociety Conference Publishing Services (CPS), which is incorporated byreference herein in its entirety.

Table 3 shows an example transaction. Transactions started with TBEGINare not assured to ever successfully complete with TEND, since they canexperience an aborting condition at every attempted execution, e.g., dueto repeating conflicts with other CPUs. This requires that the programsupport a fallback path to perform the same operationnon-transactionally, e.g., by using traditional locking schemes. Thisputs significant burden on the programming and software verificationteams, especially where the fallback path is not automatically generatedby a reliable compiler.

TABLE 3 Example Transaction Code LHI R0,0 *initialize retry count=0 loopTBEGIN *begin transaction JNZ abort *go to abort code if CC1=0 LT R1,lock *load and test the fallback lock JNZ lckbzy *branch if lock busy .. . perform operation . . . TEND *end transaction . . . . . . . . . . .. lckbzy TABORT *abort if lock busy; this *resumes after TBEGIN abort JOfallback *no retry if CC=3 AHI R0, 1 *increment retry count CIJNL R0,6,*give up after 6 attempts fallback PPA R0, TX *random delay based onretry count . . . potentially wait for lock to become free . . . J loop*jump back to retryfallback OBTAIN lock *using Compare&Swap . . .perform operation . . . RELEASE lock . . . . . . . . . . . .

The requirement of providing a fallback path for aborted TransactionExecution (TX) transactions can be onerous. Many transactions operatingon shared data structures are expected to be short, touch only a fewdistinct memory locations, and use simple instructions only. For thosetransactions, the IBM zEnterprise EC12 introduces the concept ofconstrained transactions; under normal conditions, CPU 114 (FIG. 2)assures that constrained transactions eventually end successfully,albeit without giving a strict limit on the number of necessary retries.A constrained transaction starts with a TBEGINC instruction and endswith a regular TEND. Implementing a task as a constrained ornon-constrained transaction typically results in very comparableperformance, but constrained transactions simplify software developmentby removing the need for a fallback path. IBM's Transactional Executionarchitecture is further described in z/Architecture, Principles ofOperation, Tenth Edition, SA22-7832-09 published September 2012 fromIBM, incorporated by reference herein in its entirety.

A constrained transaction starts with the TBEGINC instruction. Atransaction initiated with TBEGINC must follow a list of programmingconstraints; otherwise the program takes a non-filterableconstraint-violation interruption. Exemplary constraints may include,but not be limited to: the transaction can execute a maximum of 32instructions, all instruction text must be within 256 consecutive bytesof memory; the transaction contains only forward-pointing relativebranches (i.e., no loops or subroutine calls); the transaction canaccess a maximum of 4 aligned octowords (an octoword is 32 bytes) ofmemory; and restriction of the instruction-set to exclude complexinstructions like decimal or floating-point operations. The constraintsare chosen such that many common operations like doubly linkedlist-insert/delete operations can be performed, including the verypowerful concept of atomic compare-and-swap targeting up to 4 alignedoctowords. At the same time, the constraints were chosen conservativelysuch that future CPU implementations can assure transaction successwithout needing to adjust the constraints, since that would otherwiselead to software incompatibility.

TBEGINC mostly behaves like XBEGIN in TSX or TBEGIN on IBM's zEC12servers, except that the floating-point register (FPR) control and theprogram interruption filtering fields do not exist and the controls areconsidered to be zero. On a transaction abort, the instruction addressis set back directly to the TBEGINC instead of to the instruction after,reflecting the immediate retry and absence of an abort path forconstrained transactions.

Nested transactions are not allowed within constrained transactions, butif a TBEGINC occurs within a non-constrained transaction it is treatedas opening a new non-constrained nesting level just like TBEGIN would.This can occur, e.g., if a non-constrained transaction calls asubroutine that uses a constrained transaction internally.

Since interruption filtering is implicitly off, all exceptions during aconstrained transaction lead to an interruption into the operatingsystem (OS). Eventual successful finishing of the transaction relies onthe capability of the OS to page-in the at most 4 pages touched by anyconstrained transaction. The OS must also ensure time-slices long enoughto allow the transaction to complete.

TABLE 4 Transaction Code Example TBEGINC *begin constrained transaction. . . perform operation . . . TEND *end transaction

Table 4 shows the constrained-transactional implementation of the codein Table 3, assuming that the constrained transactions do not interactwith other locking-based code. No lock testing is shown therefore, butcould be added if constrained transactions and lock-based code weremixed.

When failure occurs repeatedly, software emulation is performed usingmillicode as part of system firmware. Advantageously, constrainedtransactions have desirable properties because of the burden removedfrom programmers.

With reference to FIG. 3, the IBM zEnterprise EC12 processor introducedthe transactional execution facility. The processor can decode 3instructions per clock cycle; simple instructions are dispatched assingle micro-ops, and more complex instructions are cracked intomultiple micro-ops. The micro-ops (Uops 232 b) are written into aunified issue queue 216, from where they can be issued out-of-order. Upto two fixed-point, one floating-point, two load/store, and two branchinstructions can execute every cycle. A Global Completion Table (GCT)232 holds every micro-op 232 b and a transaction nesting depth (TND) 232a. GCT 232 is written in-order at decode time, tracks the executionstatus of each micro-op 232 b, and completes instructions when allmicro-ops 232 b of the oldest instruction group have successfullyexecuted.

Level 1 (L1) 240 is a data cache. L1 240 is a 96 KB (kilo-byte) 6-wayassociative cache with 256 byte cache-lines and 4 cycle use latency,coupled to a private 1 MB (mega-byte) 8-way associative 2nd-level (L2)268. L2 268 is a data cache with 7 cycles use-latency penalty for L1 240misses. L1 240 is the cache closest to a processor and Ln cache is acache at the nth level of caching. Both L1 240 and L2 268 arestore-through caches. Six cores on each central processor (CP) chipshare a 48 MB 3rd-level store-in cache, and six CP chips are connectedto an off-chip 384 MB 4th-level cache, packaged together on a glassceramic multi-chip module (MCM). Up to 4 multi-chip modules (MCMs) canbe connected to a coherent symmetric multi-processor (SMP) system withup to 144 cores (not all cores are available to run customer workload).

Coherency is managed with a variant of the MESI protocol. Cache-linescan be owned read-only (shared) or exclusive; L1 240 and L2 268 arestore-through caches and thus do not contain dirty lines. L3 272 and L4cache (not shown) are store-in and track dirty states. Each cache isinclusive of all its connected lower level caches.

Coherency requests are called “cross interrogates” (XI) and are senthierarchically from higher level to lower-level caches, and between theL4s. When one core misses the L1 240 and L2 268 and requests the cacheline from its local L3 272, L3 272 checks whether it owns the line, andif necessary sends an XI to the currently owning L2 268/L1 240 underthat L3 272 to ensure coherency, before it returns the cache line to therequestor. If the request also misses the L3 272, then L3 272 sends arequest to the L4 cache (not shown), which enforces coherency by sendingXIs to all necessary L3s under that L4, and to the neighboring L4s. Thenthe L4 responds to the requesting L3 which forwards the response to L2268/L1 240.

Note that due to the inclusivity rule of the cache hierarchy, sometimescache lines are XI'ed from lower-level caches due to evictions onhigher-level caches caused by associativity overflows from requests toother cache lines. These XIs can be called “LRU XIs”, where LRU standsfor least recently used.

Making reference to yet another type of XI requests, Demote-XIstransition cache-ownership from exclusive into read-only state, andExclusive-XIs transition cache ownership from exclusive into invalidstate. Demote-XIs and Exclusive-XIs need a response back to the XIsender. The target cache can “accept” the XI, or send a “reject”response if it first needs to evict dirty data before accepting the XI.L1 240/L2 268 caches are store through, but may reject demote-XIs andexclusive XIs if they have stores in their store queues that need to besent to L3 before downgrading the exclusive state. A rejected XI will berepeated by the sender. Read-only-XIs are sent to caches that own theline read-only; no response is needed for such XIs since they cannot berejected. The details of the SMP protocol are similar to those describedfor the IBM z10 by P. Mak, C. Walters, and G. Strait, in “IBM System z10processor cache subsystem microarchitecture”, IBM Journal of Researchand Development, Vol 53:1, 2009, which is incorporated by referenceherein in its entirety.

Transactional Instruction Execution

FIG. 3 depicts example components of an example CPU environment 112,including a CPU 114 and caches/components with which it interacts (suchas those depicted in FIGS. 1 and 2). Instruction decode unit (IDU) 208keeps track of the current transaction nesting depth (TND) 212. When IDU208 receives a TBEGIN instruction, TND 212 is incremented, andconversely decremented on TEND instructions. TND 212 is written into GCT232 for every dispatched instruction. When a TBEGIN or TEND is decodedon a speculative path that later gets flushed, TND 212 of IDU 208 isrefreshed from the youngest GCT 232 entry that is not flushed. Thetransactional state is also written into issue queue 216 for consumptionby the execution units, mostly by Load/Store Unit (LSU) 280, which alsohas an effective address calculator 236 that is included in LSU 280. TheTBEGIN instruction may specify a transaction diagnostic block (TDB) forrecording status information, should the transaction abort beforereaching a TEND instruction.

Similar to the nesting depth, IDU 208/GCT 232 collaboratively track theaccess register/floating-point register (AR/FPR) modification masksthrough the transaction nest; IDU 208 can place an abort request intoGCT 232 when an AR/FPR-modifying instruction is decoded and themodification mask blocks that. When the instruction becomesnext-to-complete, completion is blocked and the transaction aborts.Other restricted instructions are handled similarly, including TBEGIN ifdecoded while in a constrained transaction, or exceeding the maximumnesting depth.

An outermost TBEGIN is cracked into multiple micro-ops depending on theGR-Save-Mask; each micro-op 232 b (including, for example uop 0, uop 1,and uop2) will be executed by one of the two fixed point units (FXUs)220 to save a pair of GR 228 into a special transaction-backup registerfile 224, that is used to later restore the content of the pair of GR228 in case of a transaction abort. Also, the TBEGIN spawns micro-ops232 b to perform an accessibility test for the TDB if one is specified;the address is saved in a special purpose register for later usage inthe abort case. At the decoding of an outermost TBEGIN, the instructionaddress and the instruction text of the TBEGIN are also saved in specialpurpose registers for a potential abort processing later on.

TEND and NTSTG are single micro-op 232 b instructions; NTSTG(non-transactional store) is handled like a normal store except that itis marked as non-transactional in issue queue 216 so that LSU 280 cantreat it appropriately. TEND is a no-op at execution time, the ending ofthe transaction is performed when TEND completes.

As mentioned, instructions that are within a transaction are marked assuch in issue queue 216, but otherwise execute mostly unchanged; LSU 280performs isolation tracking as described in the next section.

Since decoding is in-order, and since IDU 208 keeps track of the currenttransactional state and writes it into issue queue 216 along with everyinstruction from the transaction, execution of TBEGIN, TEND, andinstructions before, within, and after the transaction can be performedout-of order. It is even possible (though unlikely) that TEND isexecuted first, then the entire transaction, and lastly the TBEGINexecutes. Program order is restored through GCT 232 at completion time.The length of transactions is not limited by the size of GCT 232, sincea general purpose register (GR) 228 can be restored from backup registerfile 224.

During execution, the program event recording (PER) events are filteredbased on the Event Suppression Control, and a PER TEND event is detectedif enabled. Similarly, while in transactional mode, a pseudo-randomgenerator may be causing the random aborts as enabled by the TransactionDiagnostics Control.

Tracking for Transactional Isolation

Load/Store Unit 280 tracks cache lines that were accessed duringtransactional execution, and triggers an abort if an XI from another CPU(or an LRU-XI) conflicts with the footprint. If the conflicting XI is anexclusive or demote XI, LSU 280 rejects the XI back to L3 272 in thehope of finishing the transaction before L3 272 repeats the XI. This“stiff-arming” is very efficient in highly contended transactions. Inorder to prevent hangs when two CPUs stiff-arm each other, a XI-rejectcounter is implemented, which triggers a transaction abort when athreshold is met.

L1 cache directory 240 is traditionally implemented with static randomaccess memories (SRAMs). For the transactional memory implementation,valid bits 244 (64 rows×6 ways) of the directory have been moved intonormal logic latches, and are supplemented with two more bits per cacheline: TX-read 248 and TX-dirty 252 bits.

TX-read 248 bits are reset when a new outermost TBEGIN is decoded (whichis interlocked against a prior still pending transaction). A TX-read 248bit is set at execution time by every load instruction that is marked“transactional” in the issue queue. Note that this can lead toover-marking if speculative loads are executed, for example on amispredicted branch path. The alternative of setting the TX-read 248 bitat load completion time was too expensive for silicon area, sincemultiple loads can complete at the same time, requiring many read-portson the load-queue.

Stores execute the same way as in non-transactional mode, but atransaction mark is placed in store queue (STQ) 260 entry of the storeinstruction. At write-back time, when the data from STQ 260 is writteninto L1 240, a TX-dirty bit 252 in L1-directory 256 is set for thewritten cache line. Store write-back into L1 240 occurs only after thestore instruction has completed, and at most one store is written backper cycle. Before completion and write-back, loads can access the datafrom STQ 260 by means of store-forwarding; after write-back, CPU 114(FIG. 2) can access the speculatively updated data in L1 Cache 240. Ifthe transaction ends successfully, the respective TX-dirty bit 252 ofall cache-lines are cleared, and also the TX-marks of not yet writtenstores are cleared in STQ 260, effectively turning the pending storesinto normal stores.

On a transaction abort, all pending transactional stores are invalidatedfrom STQ 260, even those already completed. All cache lines that weremodified by the transaction in L1 Cache 240, that is, have TX-dirty bit252 on, have their valid bits turned off, effectively removing them fromL1 Cache 240 cache instantaneously.

The architecture requires that before completing a new instruction, theisolation of the transaction read- and write-set is maintained. Thisisolation is ensured by stalling instruction completion at appropriatetimes when XIs are pending; speculative out-of order execution isallowed, optimistically assuming that the pending XIs are to differentaddresses and not actually cause a transaction conflict. This designfits very naturally with the XI-vs-completion interlocks that areimplemented on prior systems to ensure the strong memory ordering thatthe architecture requires.

When L1 Cache 240 receives an XI, L1 Cache 240 accesses the directory tocheck validity of the XI'ed address in L1 Cache 240, and if TX-read bit248 is active on the XI'ed line and the XI is not rejected, LSU 280triggers an abort. When a cache line with active TX-read bit 248 isLRU'ed from L1 Cache 240, a special LRU-extension vector remembers foreach of the 64 rows of L1 Cache 240 that a TX-read line existed on thatrow. Since no precise address tracking exists for the LRU extensions,any non-rejected XI that hits a valid extension row LSU 280 triggers anabort. Providing the LRU-extension effectively increases the readfootprint capability from the L1-size to the L2-size and associativity,provided no conflicts with other CPUs 114 (FIGS. 1 and 2) against thenon-precise LRU-extension tracking causes of aborts.

The store footprint is limited by the store cache size (the store cacheis discussed in more detail below) and thus implicitly by the size andassociativity of L2 Cache 268. No LRU-extension action needs to beperformed when a TX-dirty 252 cache line is LRU'ed from L1 Cache 240.

Store Cache

In prior systems, since L1 Cache 240 and L2 Cache 268 are store-throughcaches, every store instruction causes an L3 272 store access; with now6 cores per L3 272 and further improved performance of each core, thestore rate for L3 272 (and to a lesser extent for L2 Cache 268) becomesproblematic for certain workloads. In order to avoid store queuingdelays, a gathering store cache 264 had to be added, that combinesstores to neighboring addresses before sending them to L3 272.

For transactional memory performance, it is acceptable to invalidateevery TX-dirty 252 cache line from L1 Cache 240 on transaction aborts,because L2 Cache 268 cache is very close (7 cycles L1 Cache 240 misspenalty) to bring back the clean lines. However, it would beunacceptable for performance (and silicon area for tracking) to havetransactional stores write L2 Cache 268 before the transaction ends andthen invalidate all dirty L2 Cache 268 cache lines on abort (or evenworse on the shared L3 272).

The two problems of store bandwidth and transactional memory storehandling can both be addressed with the gathering of store cache 264.Store cache 264 is a circular queue of 64 entries, each entry holding128 bytes of data with byte-precise valid bits. In non-transactionaloperation, when a store is received from LSU 280, the store cache 264checks whether an entry exists for the same address, and if so gathersthe new store into the existing entry. If no entry exists, a new entryis written into the queue, and if the number of free entries falls undera threshold, the oldest entries are written back to L2 Cache 268 and L3272 caches.

When a new outermost transaction begins, all existing entries in thestore cache are marked closed so that no new stores can be gathered intothem, and eviction of those entries to L2 Cache 268 and L3 272 isstarted. From that point on, the transactional stores coming out of STQ260, of LSU 280, allocate new entries, or gather into existingtransactional entries. The write-back of those stores into L2 Cache 268and L3 272 is blocked, until the transaction ends successfully; at thatpoint subsequent (post-transaction) stores can continue to gather intoexisting entries, until the next transaction closes those entries again.

Store cache 264 is queried on every exclusive or demote XI, and causesan XI reject if the XI compares to any active entry. If the core is notcompleting further instructions while continuously rejecting XIs, thetransaction is aborted at a certain threshold to avoid hangs.

LSU 280 requests a transaction abort when store cache 264 overflows. LSU280 detects this condition when it tries to send a new store that cannotmerge into an existing entry, and the entire store cache 264 is filledwith stores from the current transaction. Store cache 264 is managed asa subset of the L2 Cache 268: while transactionally dirty lines can beevicted from the L1 Cache 240, they have to stay resident in the L2Cache 268 throughout the transaction. The maximum store footprint isthus limited to the store cache size of 64×128 bytes, and it is alsolimited by the associativity of the L2 Cache 268. Since the L2 Cache 268is 8-way associative and has 512 rows, it is typically large enough tonot cause transaction aborts.

If a transaction aborts, store cache 264 is notified and all entriesholding transactional data are invalidated. Store cache 264 also has amark per doubleword (8 bytes) whether the entry was written by a NTSTGinstruction—those doublewords stay valid across transaction aborts.

Millicode-Implemented Functions

Traditionally, IBM mainframe server processors contain a layer offirmware called millicode which performs complex functions like certainCISC instruction executions, interruption handling, systemsynchronization, and RAS. Millicode includes machine dependentinstructions as well as instructions of the instruction set architecture(ISA) that are fetched and executed from memory similarly toinstructions of application programs and the operating system (OS).Firmware resides in a restricted area of main memory that customerprograms cannot access. When hardware detects a situation that needs toinvoke millicode, the instruction fetching unit 204 switches into“millicode mode” and starts fetching at the appropriate location in themillicode memory area. Millicode may be fetched and executed in the sameway as instructions of the instruction set architecture (ISA), and mayinclude ISA instructions.

For transactional memory, millicode is involved in various complexsituations. Every transaction abort invokes a dedicated millicodesub-routine to perform the necessary abort steps. The transaction-abortmillicode starts by reading special-purpose registers (SPRs) holding thehardware internal abort reason, potential exception reasons, and theaborted instruction address, which millicode then uses to store a TDB ifone is specified. The TBEGIN instruction text is loaded from an SPR toobtain the GR-save-mask, which is needed for millicode to know which GRs228 to restore.

The CPU (e.g., CPUs 114 a, b of FIG. 1) supports a specialmillicode-only instruction to read out the TX backup-GRs 224 and copythem into the main GRs 228. The TBEGIN instruction address is alsoloaded from an SPR to set the new instruction address in the PSW tocontinue execution after the TBEGIN once the millicode abort sub-routinefinishes. That PSW may later be saved as program-old PSW in case theabort is caused by a non-filtered program interruption.

The TABORT instruction may be millicode implemented; when the IDU 208decodes TABORT, it instructs the instruction fetch unit to branch intoTABORT's millicode, from which millicode branches into the common abortsub-routine.

The Extract Transaction Nesting Depth (ETND) instruction may also bemillicoded, since it is not performance critical; millicode loads thecurrent nesting depth out of a special hardware register and places itinto GRs 228. The PPA instruction is millicoded; it performs the optimaldelay based on the current abort count provided by software as anoperand to PPA, and also based on other hardware internal state.

For constrained transactions, millicode may keep track of the number ofaborts. The counter is reset to 0 on successful TEND completion, or ifan interruption into the OS occurs (since it is not known if or when theOS will return to the program). Depending on the current abort count,millicode can invoke certain mechanisms to improve the chance of successfor the subsequent transaction retry. The mechanisms involve, forexample, successively increasing random delays between retries, andreducing the amount of speculative execution to avoid encounteringaborts caused by speculative accesses to data that the transaction isnot actually using. As a last resort, millicode can broadcast to otherCPUs (e.g., CPUs 114 a, b of FIG. 1) to stop all conflicting work, retrythe local transaction, before releasing the other CPUs 114 to continuenormal processing. Multiple CPUs (e.g., CPUs 114 a, b of FIG. 1) must becoordinated to not cause deadlocks, so some serialization betweenmillicode instances on different CPUs (see FIG. 1, CPUs 114 a, b) isrequired.

A nested transaction is a transaction that is performed within anothertransaction. The transaction in which a nested transaction is nested isreferred to as its “outer” transaction. When a nested transaction fails,all changes made within the nested transaction are rolled back. However,the failure of the nested transaction does not necessarily cause itsouter transaction to fail. Whether the outer transaction fails inresponse to the failure of a nested transaction is determined by thelogic of the outer transaction.

Transactions may be nested, and can be classified as open or closednested. If a thread is currently executing a transaction and reaches thestart of a new transaction, this atomic block is executed as a closednested child transaction of the currently-executing parent. This nestedtransaction executes within the same isolation boundary as the enclosingtransaction, and just like other memory accesses of the enclosingtransaction, the effects of the nested transaction will only becomevisible when the enclosing transaction commits. In other words, theparent transaction is effectively suspended, and the closed nestedtransaction is allowed to run to completion before processing in theparent is resumed. When a nested transaction rolls back, its temporaryeffects are undone and the state of the parent transaction is restoredto the point that the nested child transaction began. Two knowntechniques for combining a child transaction with a parent transactionare collapsed nesting and closed nesting.

Collapsed nesting is a technique for combining transaction nesting.Collapsed nesting involves subsuming all nested transactions into theirtop-level ancestor. In an example scheme known in the art, the nestedbegin/end transaction instructions are not processed except to update anest depth counter; only when this counter is 0 after an end transactiondoes a transaction commit.

An alternative to a technique of collapsed nesting is closed nesting, inwhich only aborted transactions and their descendants, not their entireancestry, are prone to being rolled back. Closed nesting offers apotential performance advantage in, for example, the case of a longtransaction seeking to acquire a highly contended resource. In a closednesting policy, enclosing the lock acquisition in a nested transactionof its own limits the cost of conflicting on the contended lock to onlya few rolled-back instructions. Other performance justifications forsupporting closed nesting may be advanced; however, it must be notedthat after a nested transaction commits, the entire read and write setof the nested transaction(s) are merged into its parent transaction,exposing the parent to potential conflict.

The merging of a parent transaction with a child transaction typicallycarries a number of inherent risks. For example, as child transactionsare merged with the parent transaction, the footprint of the parentbecomes larger. In other words, the amount of resources needed toprocess the parent becomes larger as child transactions are merged withthe parent. This can lead to several complications. First, there areoften system limitations that constrain the maximum allowable size of agiven transaction yielding a size limit for merged transactions. Second,competition for a popular resource can be fierce, leading to delays intransaction processing if the merged transaction requires that resource.Third, as the merged transaction grows in size the transaction typicallyrequires more time to be processed. As such, there is an increasedchance that a value being used by the transaction may be read or writtento by another transaction, leading to an abort of the mergedtransaction. Fourth, if an conflict arises with a child transaction of amerged transaction, then the parent may itself may experience aresulting conflict leading to an abort of the merged transaction.

These complications are likely to become even more pronounced if twooutmost transactions are combined to form a single transaction. Aconsequence of combining two outmost transactions is the generation of amuch larger footprint (e.g., a cache memory footprint) for thetransaction, which leads to an increased risk of the transaction beingaborted. For at least this reason, in the known art, two outmosttransactions are not combined to form a single transaction. Such acombination within the known art could result in numerous conflicts thatwould render many known transaction processing techniques inoperable orvery inefficient. However, in the following discussion, a technique ofcombining two or more outmost transactions to increase performance, aprocess herein denoted as “coalescing”, will be discussed.

Hardware support for transactional memory in computing systems attemptsto guarantee that the contents of a hardware transaction are executedatomically. That is, a hardware transaction takes effect in its entiretyor not at all. The hardware keeps track of the fetch and storefootprint, i.e., a memory footprint, encountered within a transactionwith a cache line granularity. A memory footprint includes the addressesin memory that are read from or written to during the processing of atransaction. Fetches and stores made to memory addresses cached in theselines in a transaction appear to be performed atomically. In addition,the hardware saves the contents of the general registers (e.g., thenumber of general registers, and which register can be saved, can bedefined in the TBEGIN instruction), instruction address of a transactionbegin instruction, program status word value (PSW), and otherarchitected and micro-architected registers before the start of thetransaction. In case of an abort, hardware restores back the values.

To limit the number of cache lines to observe as subset of the cachefootprint, and to reduce the number of backup registers to be restoredin case of an abort, hardware can limit the number of “active” outertransaction in the pipeline. In some instances, this is because, amongother things, each outer transaction has its own backup register values,in case it gets aborted, and its own cache footprint. In some systemsthe hardware limits the number of outmost transactions from dispatch tocompletion to only one. Such a restrictive pipeline can limit the rateat which transactions are processed and lead to a bottleneck oftransactions to be processed. In such a case, the hardware stalls thepipeline at the decode or dispatch areas once a new transaction isdecoded, while there is still another transaction that is not yetcompeted. The stalling of the new outer transaction in decode ordispatch stage (in implementation, the outer transaction begininstruction and all following (i.e., younger) instructions are oftenheld) can reduce the need for additional backup registers and additionalmonitors of its cache footprint.

In certain circumstances, outmost transactions are of close proximity.As a result of the close proximity, pipeline stalls or pipeline bubblesare incurred, causing significant performance degradation. An outermosttraction can be of a single depth or can instead include nestedtransactions. By coalescing two or more outermost transactions into asingle transaction, pipeline stalls or pipeline bubbles can be reduced.

Turning now to FIGS. 4-8, each outermost transactions has its own cachefootprint and a transaction dependent value of general register contentsthat need to be restored if the transaction is aborted. A cachefootprint is a map of all cache lines touched by memory operand accessesof the transaction. If, however, two or more outermost transactions arecoalesced into a single transaction, then the footprints of thetransactions are merged into a single footprint (a coalesced footprint).However, the backup registers are still configured for the original,i.e., non-coalesced, transactions. Therefore, in the case of an abort,the hardware rolls back to the start of the oldest transaction of thecoalesced set and does not store any transaction store data of thecoalesced transactions to memory. If the coalesced set of transactionscomplete, all store data of the coalesced transacts are stored to memoryin a single atomic operation, as observed by other processors.

In one embodiment, the processor monitors the end of a transaction(i.e., the outermost transaction end instruction) and determines if thattransaction should be coalesced into another transaction when a newtransaction start (transaction begin instruction) is identified. Whentwo outermost transactions are coalesced, the non-transactionalinstructions between them, if any exist, that would previously have beenexecuted non-transactionally, may be executed transactionally instead.There are a number of possible factors that can be used to make such adetermination. Many such factors can be categorized for example asthreshold limits or history of successful transaction processing postcoalescence or instruction specific characteristics. For example, onefactor can be the number of instructions between the outermosttransaction end instruction of the first transaction and the outermosttransaction begin instruction of another. This factor can be expressedas a threshold limit. If there are too many instructions between theoutermost transaction end instruction of the first transaction and theoutermost TBEGIN of another then those transactions will not becoalesced.

In a second example, a factor can be projected instructions per cycle(IPC). Even if the number of instructions between two transactions islow, the instructions may be micro-encoded or have long latencyoperations that require a large number of execution cycles to complete.Therefore, the projected IPC can be a helpful factor when determiningwhether or not to coalesce a given transaction with another. If theprojected IPC exceeds a threshold then the transactions will not becoalesced.

A third factor can be the class to which the instructions between twotransactions belong. If such instructions do not belong to a certainclass, then coalescing those two transactions could lead to an abort.Therefore, the class of instructions located between two transactionscan be a useful factor to take into account when determining whether ornot to coalesce two outmost transactions. If the instructions do notbelong to the required class then the transactions will not becoalesced.

A fourth factor can be the history of prior occurrences of theidentified transactions. A history that indicates the transactions havebeen coalesced without an abort can be a good indicator that thetransactions can be coalesced again and processed together as a singletransaction.

A fifth factor can be a threshold limit on the number of transactionsthat can be coalesced. For example, due to the increased risk of abortas the number of coalesced transactions increases, a threshold limit offive is employed. Therefore, if five transactions have already beencoalesced then a sixth transaction will not be added.

A sixth factor can be the limitations of resources that are available.This can be compared to the historical size of a given transaction, suchas the size of instructions, footprint size, stores buffer usage,distinct cache lines etc. In general as a transaction increases in sizethere is an increase in the footprint size of the transaction. Thisfootprint includes the resources required to execute the transaction.This can become a limiting factor when transactions are being coalesced.As such, the size of a footprint of a coalesced transaction is used todetermine if additional coalescing is possible. For example, threetransactions have been coalesced and there are excess resources stillavailable. A fourth transaction is identified and the resources requiredto process the transaction are analyzed. A comparison between theamounts of available resources to the resources required to process thetransaction can yield a determination as to whether the fourthtransaction should be coalesced. The resources required by the coalescedtransaction should not exceed the available resources since this willlead to an abort. One example of such a resource is a number of cachelines needed by the coalesced transactions. Another example of such aresource is a number of cache lines of a congruence class needed by thecoalesced transaction (an 8 way set+associative cache can not support atransaction needing more than 8 cache lines in a set). Multi-treadedprocessors may have further resource limitations to permit concurrentexecution of transactions on multiple threads.

A seventh, factor can be the number of times a given transaction hasbeen previously aborted. If the number of logged aborts for thattransaction exceeds a threshold, then it could be wasteful to coalescethat transaction with another. As such, if the number of logged abortsfor that transaction exceeds the threshold, then the transactions willnot be coalesced. A transaction may be identified by, for example, theaddress of the transaction begin instruction that starts thetransaction, or an identifier value associated with each transaction.

In many embodiments, there is a limit as to the number of transactionsthat can be coalesced. This number can be hardwired, programmed or canbe dynamically chosen by hardware. In some embodiments, if there is anabort of a transaction, then the coalescing function determines if theaborted transaction was a coalesced transaction. If the abortedtransaction was a coalesced transaction, then the limit as to the numberof transactions that can be coalesced may be temporarily set to one andthe transactions retried individually, i.e., not coalesced. If theaborted transaction was not a coalesced transaction, then thattransaction is handled as a normal abort. In some embodiments, the limitas to the number of transactions that can be coalesced may be reduced byone each time a given coalesced transaction is aborted. For example, iffive transactions are coalesced and that coalesced transaction leads toan abort then the limit as to the number of transactions that can becoalesced would be reduced to four. A new coalesced transaction wouldthen be created and be processed using the new lower limit. However, incertain situations certain transactions may not be coalesced accordingto a machine dependent protocol for coalescing. For example, if there isa transaction T, and the instructions of a prior transaction T−1 arebeyond a certain pipeline stage, e.g., are about to complete, thentransaction T may not be coalesced with transaction T−1.

In some embodiments, a checkpoint is defined at the boundary of eachoutermost transaction. A checkpoint boundary is used to identify whichpart of a transaction footprint, of a coalesced transaction, correspondsto each respective transaction that was coalesced. In the case of anabort, these checkpoints can be used as return points. For example, ifT1, T2, T3 and T4 are non-nested transactions which are coalesced andthere is an abort due to T4, then the footprint can be analyzed and thesection of the footprint corresponding to transaction T4 can be isolatedand the rest of the footprint corresponding to T1, T2 and T3 can becommitted. Thus, only the transaction T4 would require re-execution asan outermost transaction and not the entire coalesced transaction.However, this is not the case if T1-T4 is nested transactions. If T1-T4include nested transactions, then T1-T3 cannot be committed.

To handle an abort using such a checkpoint, the transaction can beisolated to a certain checkpoint boundary. For example, if there is amemory cross interrogate that affects transaction T when M transactionsare coalesced and T is less than or equal to M, then commit transactions1 to T−1 and restore back to start again at transaction T. One method tomark checkpoint boundaries is through the instruction address of anoutermost transaction begin instruction(s). In general as transactionsize increases there is a corresponding increase in the time it takes tocomplete the transaction, which increases chances of an abort occurringsince other processors/threads have more time to generate conflicts.However, through the use of checkpoint boundaries, the potentialdecreased performance due to increased transaction size can be mitigatedsince only the transactions directly affected by the conflict will needto be re-executed.

In one embodiment, non-transactional instructions that exist between twotransactions require consideration. In certain embodiments, instructionsthat are not part of any transaction can be marked as transactionalinstructions when transactions that are architecturally older andyounger are than those instructions are coalesced. This can be of usewhen an abort condition leads to a return to the first transaction ofthe coalesced set of transactions. Certain instructions may berestricted from being included as part of a transaction. Instructionsthat are not part of, or can not be a part of, any transaction may bemarked as not being part of any transaction. For example, in the casewhere checkpoint boundaries have been applied, there is a loadinstruction that has been marked as being part of a transaction andanother load instruction that is marked as non-transactional. If anabort occurs then the non-transactional load value can be saved andtracked. This means that less work needs to be done in the future sincethe loaded value still exists. However, the transactional loadinstruction will have to be repeated. In another example, a storeinstruction is transactional. The address of the stored value is addedto the footprint of the transaction and that stored value is observedfor conflict.

In some embodiments, a dynamic predictor is employed to aid in thedetermination of whether transactions should be coalesced. There are twostarting states, i.e., initial states for transaction history, which canbe used for such a predictor. In both cases, changes are made totransaction history as transactions are completed.

The first starting state is a historical state where it is assumed thatall transactions can not be coalesced. When prompted, coalescingactivity commences and the history is updated to reflect whethercoalesced transactions were successfully executed, i.e., were committed,or were aborted. The updated history can then be used to guide futurecoalescing activity. The history can include a transaction identifier(e.g., a transaction begin address) the footprint size of a transaction,size of instructions of the transaction, and other data that can be usedto determine whether a given transaction can be coalesced.

The second starting state is a state where it is assumed that alltransactions can be coalesced. As above, coalescing activity commencesand the history is updated to reflect whether coalesced transactionswere successfully executed or were aborted. In such a situation,transactions are coalesced whenever possible and this information issaved as part of a history. The history would therefore indicate that agiven transaction has been coalesced based on transaction identifier ofcoalesced transactions, for example, information such as transactionbegin instruction address.

In certain embodiments, a flag, a hardware protected bit, is set fortransactions as an indication to help direct coalescing activity. Afirst flag can be used to indicate that a given transaction has beensuccessfully coalesced with architecturally younger (i.e., following)transaction, and a second flag can be used to indicate that the giventransaction has been successfully coalesced with an architecturallyolder one. The use of flagging can be extended to provide furthercoalescing capability and increased completion of coalescedtransactions, i.e., a decreased number of aborted coalescedtransactions. If a coalesced transaction is aborted, then the abortreason can be examined. If it is determined that the reason for theabort is due to the coalescing of two or more transactions, then theyounger transaction is flagged to indicate that the younger transactioncannot be coalesced with architecturally older (i.e., preceding)transactions. Further, the older transaction can be flagged to indicatethat the older transaction cannot be coalesced with architecturallyyounger transactions. In some embodiments a rating system is applied toindicate how likely a given transaction can be successfully coalescedwith another transaction without a resulting abort. For example atransaction can have a weak, medium or strong coalescing flag toindicate the potential of a given transaction being successfullycoalesced. Preferably, flags are updated each time a given transactionis processed.

Such flagging of transactions can be useful to differentiate betweenindividual transactions and to help direct future coalescing activity.For example, when T1, T2, T3 and T4 transactions are coalesced togetherand a resulting abort is due to the fact that T1 and T4 are coalesced,then only T4 is flagged to indicate that it cannot be coalesced witharchitecturally older transaction. Alternatively, T1 can be flagged toindicate that T1 cannot be coalesced with architecturally youngertransactions, or T1 can be flagged to indicate that T1 cannot becoalesced with an architecturally younger transaction if that youngertransaction is already coalesced with one or more other transactions.Then, in future coalescing activity, the flags of T1 and T4 can be usedto determine whether or not those transactions should be coalesced withother transactions. Finally, if a coalesced transaction completessuccessfully, a flag is set to indicate that this transaction can becoalesced with younger and older transactions. Example functionality ofa dynamic hardware predictor that uses transaction history and flags todirect future coalescing activity is described in detail in thediscussion of FIG. 6. In this embodiment, the prediction of coalescingsuccess is handled purely in hardware. In other embodiments, thisfunction may be handled purely in software or in a combination ofhardware and software.

In some embodiments, there may be indicators which can be used tocontrol transaction coalescing activity. To that end, a controlindicator program for adding general indicators that control transactioncoalescing activity is described in detail in the discussion of FIG. 7.Such general indicators are added such that, where possible, thehardware is directed to coalesce transactions. Such general indicatorsmay be added without knowledge of hardware constraints, such as currentresource availability. In one embodiment, the addition of generalindicators for coalescing is handled in a purely software embodiment. Inother embodiments, this function may be handled purely in hardware or ina combination of hardware and software. To add context to the discussionof FIG. 7, a general description of various indicators is provided inthe following paragraph.

A first indicator can be set by execution of a software instruction thatindicates to hardware to begin to coalesce transactions where possiblefrom that point forward. A second indicator can be set by execution of asoftware instruction that indicates to hardware to cease coalescingtransactions from that point forward. A third indicator can be set basedon a prefix ahead of a transaction begin (transaction begin instruction)to indicate that the transaction following the transaction begininstruction can be coalesced. A fourth indicator can be set based on aprefix ahead of a transaction begin (transaction begin instruction) toindicate that the transaction following the transaction begininstruction can not be coalesced. A fifth indicator can be set by anoperand associated with the transaction begin instruction itself, whichindicates that the transaction can be coalesced. Yet another indicatorcan be set by an instruction to set a threshold. For example, themaximum number of transactions that can be coalesced or the maximumnumber of instruction that can be present between two transactions to becoalesced.

In certain circumstances coalescing memory transactions can negativelyimpact performance since the cache footprint of the combinedtransactions is larger than each of the individual transactions. In amulti-processor environment running many concurrent workloads, asfootprint size increases there is an increased chance that workload datacan interfere, thereby leading to a higher percentage of transactionaborts. As such, a performance gain from combining distinct transactionscan be decreased, or even lost, due to higher rate of transactionaborts. However, in other circumstances, coalescing transactions yieldsbetter performance without any visible increase in transactions beingaborted. Hardware by itself may not be able to tell when it would bebeneficial to coalesce transactions and when it would not be beneficial.Through the use of dynamic code profiling of the workloads, software canarrange code and insert hint information allowing hardware to makedeterminations as to whether coalescing distinct memory transactions isbeneficial.

In certain embodiments, hardware provides a hardware supported runtimeinstrumentation environment that can be used in real-time to gaininsights of a targeted running program. Information that cannot beobtained from pure software real-time profiling can be obtained throughthe hardware directly, e.g. information about transaction memory andtheir characteristics. Dynamic code generating environments like Java®Run-time Environment (JRE) can steer this hardware infrastructure todetermine what data to collect and how often to collect that data, andthus be enabled to create “self-tuned” run-time generated code.

In some embodiments, run-time instrumentation profile code can be usedto perform many tasks. Run-time instrumentation profile code can be usedto give hints to hardware to coalesce transactions or keep themindependent. It can be used to change code to automatically mergedistinct transactions by removing a transaction end instruction of afirst transaction and transaction begin instruction of a secondtransaction and change instructions between those two transactions tonon-transactional instructions. Run-time instrumentation profile codecan be used to add prefix instructions, i.e., an indicator, ahead of,for example, a transaction begin instruction of a transaction indicatingthat the transaction needs to be treated independently and cannot becoalesced. It can also be used to change the transaction begininstruction or transaction end instruction themselves such that thetransactions cannot be coalesced.

In some embodiments a profiler program gathers data such as reasons fora transaction being aborted, distance in the instructions between thecoalesced transactions, the type of instructions between transactions,whether any of the instructions are restricted from running in atransaction, the number of dynamic instructions in each transaction, andthe size of dynamic instructions footprint. e.g. the size of the storecache buffer needed, the number of cache line used, etc. Thisinformation can then be used to optimize the coalescing of transactionsthrough the use of dynamic code profiling of the workloads. Software canarrange code and insert hint information allowing hardware to makedeterminations as to whether coalescing distinct memory transactions arebeneficial. A coalescing optimizer 700 that optimizes the coalescing ofoutermost transactions to maximize performance gains is described indetail in the discussion of FIG. 8.

Referring now to FIGS. 1-20.

The present invention may be a system, a method, and/or a computerprogram product. The computer program product may include a computerreadable storage medium (or media) having computer readable programinstructions thereon for causing a processor to carry out aspects of thepresent invention.

The computer readable storage medium is a tangible device that canretain or store instructions for use by an instruction execution device.The computer readable storage medium may be, for example, but is notlimited to, an electronic storage device, a magnetic storage device, anoptical storage device, an electromagnetic storage device, asemiconductor storage device, or any suitable combination of theforegoing. A non-exhaustive list of more specific examples of thecomputer readable storage medium would include the following: a portablecomputer diskette, a hard disk, a random access memory (RAM), aread-only memory (ROM), an erasable programmable read-only memory (EPROMor Flash memory), a static random access memory (SRAM), a portablecompact disc read-only memory (CD-ROM), a digital versatile disk (DVD),a memory stick, a floppy disk, a mechanically encoded device such aspunch-cards or raised structures in a groove having instructionsrecorded thereon, and any suitable combination of the foregoing. Acomputer readable storage medium, as used herein, is not to be construedas being transitory signals per se, such as radio waves or other freelypropagating electromagnetic waves, electromagnetic waves propagatingthrough a waveguide or other transmission media (e.g., light pulsespassing through a fiber-optic cable), or electrical signals transmittedthrough a wire.

Computer readable program instructions described herein can bedownloaded to respective computing/processing devices from a computerreadable storage medium or to an external computer or external storagedevice via a network, for example, the Internet, a local area network, awide area network and/or a wireless network. The network may comprisecopper transmission cables, optical transmission fibers, wirelesstransmission, routers, firewalls, switches, gateway computers and/oredge servers. A network adapter card or network interface in eachcomputing/processing device receives a program from the network andforwards the program for storage in a computer readable storage mediumwithin the respective computing/processing device.

Computer readable program instructions for carrying out operations ofthe present invention may be assembler instructions,instruction-set-architecture (ISA) instructions, machine instructions,machine dependent instructions, microcode, firmware instructions,state-setting data, or either source code or object code written in anycombination of one or more programming languages, including an objectoriented programming language such as Java, Smalltalk, C++ or the like,and conventional procedural programming languages, such as the “C”programming language or similar programming languages. The programinstructions may execute entirely on the user's computer, partly on theuser's computer, as a stand-alone software package, partly on the user'scomputer and partly on a remote computer or entirely on the remotecomputer or server. In the latter scenario, the remote computer may beconnected to the user's computer through any type of network, includinga local area network (LAN) or a wide area network (WAN), or theconnection may be made to an external computer (for example, through theInternet using an Internet Service Provider).

Aspects of the present invention are described herein with reference toflowchart illustrations and/or block diagrams of methods, apparatus(systems), and computer program products according to embodiments of theinvention. It will be understood that each block of the flowchartillustrations and/or block diagrams, and combinations of blocks in theflowchart illustrations and/or block diagrams, can be implemented bycomputer readable program instructions.

These computer readable program instructions may be provided to aprocessor of a general purpose computer, special purpose computer, orother programmable data processing apparatus to produce a machine, suchthat the instructions, which execute via the processor of the computeror other programmable data processing apparatus, create means forimplementing the functions/acts specified in the flowchart and/or blockdiagram block or blocks. These computer readable program instructionsmay also be stored in a computer readable storage medium that can directa computer, a programmable data processing apparatus, and/or otherdevices to function in a particular manner, such that the computerreadable storage medium having instructions stored therein comprises anarticle of manufacture including instructions which implement aspects ofthe function/act specified in the flowchart and/or block diagram blockor blocks.

The computer readable program instructions may also be loaded onto acomputer, other programmable data processing apparatus, or other deviceto cause a series of operational steps to be performed on the computer,other programmable apparatus or other device to produce a computerimplemented process, such that the instructions which execute on thecomputer, other programmable apparatus, or other device implement thefunctions/acts specified in the flowchart and/or block diagram block orblocks.

The flowchart and block diagrams in the Figures illustrate thearchitecture, functionality, and operation of possible implementationsof systems, methods, and computer program products according to variousembodiments of the present invention. In this regard, each block in theflowchart or block diagrams may represent a module, segment, or portionof instructions, which comprises one or more executable instructions forimplementing the specified logical function(s). It should also be notedthat, in some alternative implementations, the functions noted in theblock may occur out of the order noted in the figures. For example, twoblocks shown in succession may, in fact, be executed substantiallyconcurrently, or the blocks may sometimes be executed in the reverseorder, depending upon the functionality involved. It will also be notedthat each block of the block diagrams and/or flowchart illustration, andcombinations of blocks in the block diagrams and/or flowchartillustration, can be implemented by special purpose hardware-basedsystems that perform the specified functions or acts or carry outcombinations of special purpose hardware and computer instructions.

In a first embodiment, aspects of coalescing control 300, transactioncoalescing operations 400, dynamic prediction 500, control indicator 600and coalescing optimizer 700 are included in certain hardware of FIG. 2or are stored in a computer-readable storage medium (not shown) includedas part of CPU environment 112 of FIG. 2 according to an embodiment. Inthis embodiment, hardware-based aspects of coalescing control 300,coalescing operations 400, dynamic prediction 500, control indicator 600and coalescing optimizer 700 are included as part of the physicalstructures of die 100 of FIG. 1 and CPU environment 112 of FIGS. 2 and3.

In certain embodiments, the functions and processes of coalescingcontrol 300, transaction coalescing operations 400, dynamic prediction500, control indicator 600 and coalescing optimizer 700 can be combinedin whole, or in part, to form various programs or corresponding hardwarestructures that are within the spirit and scope of the embodimentsdescribed in the discussion of FIGS. 4-8 below and in the discussionabove for hardware-based transaction execution. As such, embodiments ofthe invention may include a variety of methods, computer programproducts, and hardware structures as described in the discussion ofFIGS. 4-8 and in the discussion above. In addition, certain features andfunctions may be performed by the hardware structures described in thediscussion of FIG. 11.

Turning now to FIG. 4. FIG. 4 illustrates the operational activityexecuted by a first embodiment of coalescing control, 300, that controlsthe coalescing of one outmost transaction with another. In a firstembodiment, the control of coalescing activity is handled by software;however the actual coalescing itself is handled by hardware. In otherembodiments, the control of coalescing activity may be handled purely inhardware or in a combination of hardware and software. In still otherembodiments, the actual coalescing itself may be handled purely inhardware or in a combination of hardware and software.

In operation 305, coalescing control 300 identifies transactions and thevarious flags associated with the transactions. In decision operation310, coalescing control 300 determines if coalescing is active.Coalescing control 300 determines if coalescing is active by identifyingindicators in the code that instruct for the activation of thecoalescing process. For example, coalescing control program candetermine whether coalescing is active by identifying state informationset by a set-transaction-coalesce-mode (STCM) instruction or areset-transaction-coalesce-mode (RTCM) instruction (see the discussionof mode setter 1135 for further details regarding STCM and RTCM). Inother embodiments, indicators may not be present. In such cases, thehardware assumes that each outmost transaction has the potential to becoalesced. In this embodiment, these coalescing indicators are added bycontrol indicator 600 and coalescing optimizer 700. If such indicatorsare not present, then coalescing control 300 determines that coalescingis not active and proceeds to operation 360 (decision operation 310, nobranch). If such indicators are present, then coalescing control 300determines that coalescing is active and proceeds to operation 320(decision operation 310, yes branch).

In operation 320, coalescing control 300 identifies the coalescingfactors that are to be used when determining when two outmosttransactions are to be coalesced. This includes threshold limits such asthe number of transactions that can be coalesced, the maximum allowableprojected instructions per cycle (IPC), and the number of times a giventransaction can be previously aborted, or any of the seven factorslisted previously. The coalescing factors also include the class towhich the instructions between two transactions belong and the resourcesthat are available for transaction processing. The identified coalescingfactors are then used by coalescing control 300, in operation 330, todetermine if the two outermost transactions, if coalesced, violate anythreshold values or exceed the resources that are available fortransaction processing. For example, if there is a limit of threetransactions that can be coalesced into a single transaction and thereare already three transactions present in the coalesced transactions,then coalescing control 300 determines that a fourth transaction can notbe coalesced.

In decision operation 340, coalescing control 300 determines if, basedon the determinations of operation 330, the two outmost transactions canbe coalesced. If the two outmost transactions can not be coalesced(decision operation 340, no branch), then coalescing control 300proceeds to operation 360. If the two outmost transactions can becoalesced (decision operation 340, yes branch), then coalescing control300 proceeds to operation 350. In operation 350, coalescing control 300uses transaction coalescing operations 400 to coalesce the two outermosttransactions as well as any instructions between them, if possible. Thecoalesced transaction is then processed using transaction coalescingoperations 400.

In operation 360, coalescing control 300 processes the transactions. Theprocessed transactions may include non-coalesced transactions as well asinstructions that were not coalesced.

FIG. 5 illustrates the operational activity executed by a firstembodiment for the coalescing of outermost transactions, herein denotedtransaction coalescing operations 400. In the first embodiment describedbelow, the coalescing of transactions is handled purely in hardware,i.e., the operational activity is included as part of and is executed byhardware such as a central processing unit. In other embodiments, thecoalescing of transactions may be handled purely in software or in acombination of hardware and software.

In operation 405, of transaction coalescing operations 400, the hardwareidentifies a coalescing indication, such as a coalescing indicator addedby control indicator 600 or coalescing optimizer 700. In otherembodiments, if indicators are not being used, the hardware woulddefault to coalescing, i.e., assume that the indicator was present andproceed to operation 410. In operation 410, of transaction coalescingoperations 400, any required instructions are executed by the hardware.In operation 415, of transaction coalescing operations 400, the hardwareidentifies the transaction begin instruction, such as a TBEGIN or anXBEGIN, of an outermost transaction. An outermost transaction begininstruction that is coalesced with prior transactions is still executedin the sense of taking into account the effective controls (in certainarchitectures, these are part of the instruction text) to apply them tonested instructions. The outermost transaction begin instruction,however, does not increase the nesting depth. The nesting depth is oneand remains one. Similarly, an outermost transaction end instruction ofa coalesced transaction does not decrement the nesting depth to 0,unless it is the final transaction end instruction.

In operation 420, of transaction coalescing operations 400, the hardwareidentifies the resource limits of the hardware. Hardware resources caninclude, for example, store buffer sizes and free resources within themthat are not part of a transaction, a number of cache lines that aremonitored for existing transactions, and a count of resources of anunused line monitor. In operation 425, of transaction coalescingoperations 400 the hardware executes the instructions of thetransaction. In operation 430, of transaction coalescing operations 400,the hardware identifies any instructions that are outside of thetransaction, e.g., instructions that follow a transaction to becoalesced. Then in decision operation 435, of transaction coalescingoperations 400, the hardware determines whether the instructions locatedoutside of the transaction can be included with, i.e., processed with,the instructions of the transaction. In other words, it is determinedwhether the instructions following the transaction can be included aspart of the transaction and be processed accordingly. In general, unlessthe instruction is flagged otherwise, a given instruction can beincluded as part of the transaction as long as doing so does not exceedresource limits. If the instructions can not be included (decisionoperation 435, no branch), then the hardware operations 400 proceeds tooperation 455 of transaction coalescing operations 400. If theinstructions can be included (decision operation 435, yes branch), thenoperations 400 the hardware proceeds to decision operation 440 oftransaction coalescing operations 400.

In decision step 440, of transaction coalescing operations 400, thehardware determines whether the resource limits have been reached andwhether there are sufficient resources available to coalesce a secondtransaction with the first transaction. For example, if ninety fivepercent of the available resources are being utilized, then it isdetermined that, although the resource limits have not been reached,there are insufficient resources available to coalesce a secondtransaction with the first transaction. Typically, the instructionslocated outside the first transaction include instructions that arebetween the first and second transactions. However, in certain cases andembodiments, such outside instructions can include instructions that arenot part of a transaction, and can either precede or follow atransaction As such the resources required to process these instructionsmust also be taken into account. If it is determined that the resourcelimits have been reached or that there are insufficient resourcesavailable to coalesce a second transaction with the first transaction(decision operation 440, yes branch), then the hardware proceeds tooperation 455 of transaction coalescing operations 400. If it isdetermined that the resource limits have not been reached and that thereare sufficient resources available to coalesce a second transaction withthe first transaction (decision operation 440, no branch), then thehardware proceeds to operation 445 of transaction coalescing operations400.

In operation 445, of transaction coalescing operations 400, the hardwareidentifies a second transaction and the resource requirements of thattransaction are compared to the amount of available resources. Indecision operation 450, of transaction coalescing operations 400, thehardware determines whether the second transaction can be coalesced intothe first transaction. This determination takes into account any flagsthat are attached to the first and second transaction. For example, ifthe first or second transaction includes a flag that indicates that itcan not be coalesced with the other transaction, then it is determinedthat the transactions can not be coalesced. If the transactions can notbe coalesced (decision operation 450, no branch), then the hardwareproceeds to operation 455 of transaction coalescing operations 400. Inoperation 455, of transaction coalescing operations 400, the hardwareends the current transaction coalescing activity and the transaction isprocessed, along with any instructions that have been included with thattransaction.

If it is determined that the transactions can be coalesced (decisionoperation 450, yes branch), then the hardware proceeds to operation 460of transaction coalescing operations 400. In operation 460, oftransaction coalescing operations 400, the hardware executestransactionally the instructions of the second transaction. For example,in some cases, the hardware does not fully process the transaction endinstruction of the first transaction and the transaction begininstruction of the second transaction. However, some effective controlsof either the transaction end instruction of the first transaction orthe transaction begin instruction of the second transaction can beprocessed, thereby effectively processing the second transaction asthough it were part of the first transaction.

In decision operation 465, of transaction coalescing operations 400, thehardware determines whether an abort condition has occurred as a resultof processing the coalesced transaction. If an abort condition hasoccurred (decision operation 465, yes branch), then the hardware rollsback the coalesced transaction to the first transaction of the coalescedtransaction that aborted and abort logic is executed by the hardware, inoperation 470. If an abort condition has not occurred (decisionoperation 465, no branch), then the hardware identifies the transactionend instruction of the second transaction and the coalesced transactionis committed in step 475. In some situations, operations 405 though 460can be repeated before the execution of operation 465, therebycoalescing more transactions and instructions into the coalescedtransaction.

FIG. 6 illustrates the operational activity executed by a firstembodiment of a dynamic prediction, 500, that uses transaction historyand flags to direct future coalescing activity.

In operation 505, dynamic prediction 500 identifies the starting stateto be applied to the history. As discussed in detail above, thetransactional memory system can store a starting state and a history. Astarting state is either an assumption that coalescing is allowed forall the transaction or none of them. Then, in operation 510, dynamicprediction 500 accesses the history itself and applies the startingstate to the entries. In operation 515, dynamic prediction 500identifies coalesced transactions that have been processed.

In decision operation 520, dynamic prediction 500 determines if acoalesced transaction experienced an abort. If the coalesced transactiondid experience an abort (decision operation 520, yes branch), thendynamic prediction 500 determines the cause of the abort in operation525. If the coalesced transaction did not experience an abort (decisionoperation 520, no branch), then dynamic prediction 500 proceeds tooperation 530. In operation 530, dynamic prediction 500 applies flagsbased on either the cause of the abort or the successful execution ofthe coalesced transaction. For example, there was no abort and thecoalesced transaction was committed, as such, dynamic prediction 500applies flags accordingly. In another example, a pair of transactionthat are coalesced do not abort. As such, dynamic prediction 500 appliesflags to the transactions that were coalesced to indicate that they weresuccessfully coalesced and processed as a coalesced transaction. In yetanother example, a coalesced transaction, which includes fourtransactions that were coalesced, experiences an abort. Dynamicprediction 500 identifies that the abort was caused by the third andfourth transactions that were coalesced. Dynamic prediction 500 flagsthe fourth transaction to indicate that it can not be coalesced witholder transactions but can be coalesced with younger transactions.Dynamic prediction 500 flags the third transaction to indicate that itcan not be coalesced with younger transactions but can be coalesced witholder transactions. Finally, dynamic prediction 500 flags the first andsecond transactions to indicate that they can be coalesced with botholder and younger transactions. In some embodiments, dynamic prediction500 can flag a transaction to indicate that it cannot be coalesced witheither younger or older transactions. The flag may even be furtherqualified with a threshold for the number of transactions that can becoalesced.

In operation 535, dynamic prediction 500 updates the history to indicatethat the various transactions had been processed as a coalescedtransaction and includes the result of that processing. For example, thehistory is updated to indicate that a given set of five transactionswere successfully coalesced and processed. As such, future instances ofthose transactions would be identified for coalescing activity.

In some embodiments, dynamic prediction 500 uses the updated history topredict the results of coalescing outermost transactions that have notbeen previously coalesced. For example, a first and second outermosttransaction are coalesced and the resulting coalesced transaction iscommitted. Dynamic prediction 500 then identifies third and fourthoutermost transactions that are similar to the first and secondoutermost transactions in size, instruction type, footprint etc. Basedon the similarity, dynamic prediction 500 determines that the third andfourth outermost transactions will likely commit if coalesced and addsflags and coalescing instructions accordingly. Then based on the resultsof the coalescing, dynamic prediction 500 updates the historyaccordingly.

In some embodiments, based on the updated history, dynamic prediction500 sends a signal to coalescing optimizer 700 to increase or decreasecertain thresholds, thereby controlling coalescing activity.

FIG. 7 illustrates the operational activity executed by a firstembodiment of control indicator, 600, for identifying and handlingindicators that control transaction coalescing activity. In someembodiments, control indicator 600 is purely hardware. In someembodiments, control indicator 600 is purely software. In still otherembodiments, control indicator 600 includes a combination of bothhardware and software. In certain embodiments, control indicator 600 maynot insert instructions in the transactions, but may set predictor stateinstead.

In operation 610, control indicator 600 identifies transactions that areto be processed. In a dynamic software embodiment of control indicator600, transactions that exhibit excessive stalls, i.e., cause delays inthe completion of transactions, are identified. Transactions thatexhibit excessive stalls need to be completed before the nexttransaction can be processed. As such, a coalescing instruction or amachine state may be added such that the transaction that exhibitsexcessive stalls is not coalesced with a younger transaction. In astatic software embodiment of control indicator 600, a set of factors,such as those used in operations 320 and 330 of FIG. 4, can be used toidentify transactions that can be coalesced. For example, a thresholdnumber of instructions can be used to identify transactions that areclose enough to each other to allow coalescing.

In one embodiment, once the transactions have been identified, controlindicator 600 inserts the appropriate coalescing instruction into thecode as indicated in operation 620. In some embodiments, controlindicator 600 sets state information. Control indicator 600 insertscoalescing instruction (like, for example, a prefix ahead of atransaction begin instruction, or an argument in a transaction begininstruction itself), and then allows the hardware to determine whetherto coalesce or not. So, if there are no coalescing instructions, thenthe hardware does not attempt to coalesce. If there are coalescinginstructions, then the hardware determine whether to coalesce or not. Inmany cases, this results in the hardware attempting to coalescetransactions where possible. The transactions are then processed alongwith the coalescing instructions. Then, in operation 630, controlindicator 600 reads out instrumentation data, e.g., data aboutinstructions being sampled during runtime, from the transactionprocessing. This includes instrumentation data in either transactionabort code handling or in runtime instrumentation logic.

In decision operation 640, control indicator 600 determines if therehave been an excessive number of coalesced transaction aborts. This isusually based on a preset threshold value; however this can also bedetermined using a dynamic threshold that is adjusted to maximizeperformance. If there has been an excessive number of aborts (decisionoperation 640, yes branch), then control indicator 600 removes thecoalescing instruction to reduce the number of future aborts, inoperation 650. In other embodiments, the coalescing instruction is leftin the code by control indicator 600 but the hardware ignores it ifthere have been an excessive number of coalesced transaction aborts. Ifthere have not been an excessive number of aborts (decision operation640, no branch), then control indicator 600 leaves the coalescinginstruction as is. In some embodiments, if there have not been anexcessive number of aborts, then control indicator 600 adds additionalcoalescing instructions or sends a signal to, for example, coalescingoptimizer 700 to increase certain thresholds, thereby increasingcoalescing activity or the size of coalesced transactions.

Turning now to both FIGS. 8 and 9, a coalescing optimizer and anassociated environment will be discussed. For ease of understanding, theoperational processes utilized by a coalescing optimizer, 700, areherein described with reference to components included in FIG. 9. Anexample of a Java® Run-time Environment (JRE), which is herein denotedJRE 900, that supports the operation of coalescing optimizer 700, isillustrated as a block diagram in FIG. 9.

In accordance with a first embodiment, FIG. 8 illustrates theoperational activity executed by a first embodiment of a coalescingoptimizer 700 that optimizes coalescing of outermost transactions tomaximize performance gains. In the first embodiment, coalescingoptimizer 700 is configured to operate within a Java® Run-timeEnvironment (JRE), such as JRE 900. Coalescing optimizer 700 has accessto Just-In-Time (JIT) profiler 910, optimizer 920, code generator 930,and is in contact with the hardware, such as CPU 940 and pre-allocatedstorage 950, of FIG. 9.

In operation 710, using Just-In-Time (JIT) profiler 910, coalescingoptimizer 700 sets up a storage area, in pre-allocated storage 950,where the hardware can write runtime gathered instrumentationinformation. In operation 720, coalescing optimizer 700 uses JITprofiler 910 to insert instructions into the application to turn on oroff runtime profiling for various regions of code, and to setup theenvironment needed in the hardware for such profiling. Coalescingoptimizer 700 uses code generator 930 to incorporate the runtimeinstrumentation directives into its assembly code, which runs in theactual hardware, in operation 730.

In response to receiving the runtime instrumentation directives thehardware sets up its internal instrumentation controls as instructed bythese new directives. In operation 740, targeted information is thengathered by CPU 940, e.g. cache miss statistics, and generatesinstruction samples as setup by JIT profiler 910. The hardwareinstrumentation controls, through internal firmware and special hardwaresupport, write out of the desired instrumentation data, of instructionsbeing sampled during runtime, to the storage area, in pre-allocatedstorage 950, which was initially set up by JIT profiler 910.

In step 750, coalescing optimizer 700 uses JIT profiler 910 to analyzethe gathered instrumentation data provided by the hardware in real-time.The gathered instrumentation data can include reasons for a transactionbeing aborted, distance in the instructions between the coalescedtransactions, the type of instructions between transactions, whether anyof the instructions are restricted from running in a transaction, thenumber of dynamic instructions in each transaction, and the size ofdynamic instructions footprint, e.g. the size of the store cache bufferneeded, the number of cache line used, etc. Coalescing optimizer 700utilizes algorithms to steer optimizer 920 to generate more efficientcode, in operation 760.

Coalescing optimizer 700 then uses JIT profiler 910 to periodicallyreview the gathered instrumentation data and any changes in a run-timeenvironment of the assembly code, and re-steer optimizer 920 to adjustthe optimization of coalescing instructions according to any new runtimeenvironment changes, in operation 770.

FIG. 10 depicts a block diagram of components of a computing device,1000, that is executing coalescing control 300, dynamic prediction 500,control indicator 600 and coalescing optimizer 700, as well as anysoftware aspects of transaction coalescing operations 400, in accordancewith an illustrative first embodiment of the present disclosure. Itshould be appreciated that FIG. 10 provides only an illustration of oneimplementation and does not imply any limitations with regard to theenvironments in which different embodiments may be implemented. Manymodifications to the depicted environment may be made.

Computing device 1000 includes communications fabric 1002, whichprovides communications between computer processor(s) 1004, memory 1006,computer readable storage media 1008, communications unit 1010, andinput/output (I/O) interface(s) 1012. Communications fabric 1002 can beimplemented with any architecture designed for passing data and/orcontrol information between processors (such as microprocessors,communications and network processors, etc.), system memory, peripheraldevices, and any other hardware components within a system. For example,communications fabric 1002 can be implemented with one or more buses.

Memory 1006 and computer readable storage media 1008 arecomputer-readable storage media. In the first embodiment, memory 1006includes random access memory (RAM) 1014 and cache memory 1016. Ingeneral, memory 1006 can include any suitable volatile or non-volatilecomputer-readable storage media.

Coalescing control 300, dynamic prediction 500, control indicator 600and coalescing optimizer 700, as well as any software aspects oftransaction coalescing operations 400 are stored in computer readablestorage media 1008 for execution by one or more of the respectivecomputer processors 1004 via one or more memories of memory 1006, inaccordance with the first embodiment of the present disclosure. In thefirst embodiment, computer readable storage media 1008 includes amagnetic hard disk drive. Alternatively, or in addition to a magnetichard disk drive, computer readable storage media 1008 can include asolid state hard drive, a semiconductor storage device, read-only memory(ROM), erasable programmable read-only memory (EPROM), flash memory, orany other computer-readable storage media that is capable of storingprogram instructions or digital information.

The media used by computer readable storage media 1008 may also beremovable. For example, a removable hard drive may be used for computerreadable storage media 1008. Other examples include optical and magneticdisks, thumb drives, and smart cards that are inserted into a drive fortransfer onto another computer-readable storage medium that is also partof computer readable storage media 1008.

Communications unit 1010, in these examples, provides for communicationswith other data processing systems or devices. In these examples,communications unit 1010 includes one or more network interface cards.Communications unit 1010 may provide communications through the use ofeither or both physical and wireless communications links. Coalescingcontrol 300, dynamic prediction 500, control indicator 600 andcoalescing optimizer 700, as well as any software aspects of transactioncoalescing operations 400 may be downloaded to computer readable storagemedia 1008 through communications unit 1010.

I/O interface(s) 1012 allows for input and output of data with otherdevices that may be connected to computing device 1000. For example, I/Ointerface 1012 may provide a connection to external devices 1018 such asa keyboard, keypad, a touch screen, and/or some other suitable inputdevice. External devices 1018 can also include portablecomputer-readable storage media such as, for example, thumb drives,portable optical or magnetic disks, and memory cards. Software and dataused to practice embodiments of the present invention, e.g., coalescingcontrol 300, dynamic prediction 500, control indicator 600 andcoalescing optimizer 700, as well as any software aspects of transactioncoalescing operations 400, can be stored on such portablecomputer-readable storage media and can be loaded onto computer readablestorage media 1008 via I/O interface(s) 1012. I/O interface(s) 1012 alsoconnect to a display 1020.

Display 1020 provides a mechanism to display data to a user and may be,for example, a computer monitor.

FIG. 11 depicts various hardware structures that exist as part ofprocessor(s) 1004, of FIG. 10, in accordance with various embodiments.In certain embodiments, some of the hardware structures of FIG. 11 aresubstituted, in whole or in part, with software equivalents. Further, insome embodiments, certain hardware structures described in FIG. 11 areincluded as part of, or are configured to support the function of,coalescing control 300, dynamic prediction 500, control indicator 600coalescing optimizer 700, and transaction coalescing operations 400.

Transaction processor 1105 is a hardware structure configured to executetransaction begin instructions of outermost transactions, thetransactions themselves, transaction end instructions, coalescedtransactions, non-transaction instructions located between transactions,coalescing instructions, and memory commits of results of executedtransactions. In addition, transaction processor 1105, based onexecuting a transaction begin instruction, processes the respectivetransaction associated with the transaction begin instruction. Inaddition, if it is determined, by coalescing determiner 1110, that anoutermost transaction is not-to-be coalesced with another transaction,transaction processor 1105 commits, a first store data of that outermosttransaction to memory based on encountering the transaction endinstruction of that outermost transaction.

Coalescing determiner 1110 is a hardware structure configured todetermine whether the first transaction is to-be coalesced with a secondoutermost transaction, based on the transaction processor 1105encountering a first transaction end instruction of a first outermosttransaction. Coalescing determiner 1110 determines whether the firstoutermost transaction is to-be coalesced with a second outermosttransaction based on at least one of: a number of instructions betweenthe first outermost transaction and the second outermost transaction, atime period required to process the first outermost transaction andsecond outermost transaction, a quantity of resources required toprocess the first outermost transaction and second outermosttransaction, a maximum number of transactions that can be coalesced, anda history of coalescing outmost transactions that lead to an abortstatus. Based on the execution of one or more coalescing instructions,coalescing determiner 1110 determines whether two outermost transactionsare to be coalesced. Coalescing determiner 1110 also determines whethertwo outermost transactions are to be coalesced based on a result of anexecuted instrumentation program. If it is determined by coalescingdeterminer 1110 that a first outermost transaction and a secondoutermost transaction, of a plurality of transactions of an associatedprogram, should be coalesced, then those transactions are coalesced,using transaction coalescer 1115. Coalescing determiner 1110 alsodetermines whether two outermost transactions are to be coalesced basedon based on, at least in part, on a history of coalescing.

Threshold setter 1111 is a hardware structure configured to setthreshold values for coalescing transactions based, at least in part, onone or more coalescing instructions being executed by transactionprocessor 1105. Such threshold values are determined by threshold setter1111 based, at least in part, upon a pre-existing threshold value, ahistory of coalescing, and resource limits for processing transactions.

Transaction coalescer 1115 is a hardware structure configured tocoalesce transactions based on a determination by coalescing determiner1110 that a first outermost transaction is to-be coalesced with a secondoutermost transaction. To coalesce transactions, transaction coalescer1115 performs a method comprising: (i) not-committing store data of thefirst outermost transaction to memory prior to processing the secondoutermost transaction; (ii) based on encountering a second transactionbegin instruction of the second outermost transaction, processing thesecond transaction; (iii) based on the processing the second transactionencountering a second transaction end instruction of the secondoutermost transaction, and (iv) committing the store data of thecoalesced first outermost transaction and second outermost transactionto memory. If it is determined, by instruction handler 1120, that one ormore instructions following the first outermost transaction can beprocessed as part of the coalesced transactions, transaction coalescer1115 executes the one or more instructions following the first outermosttransaction as part of the coalesced first outermost transaction andsecond outermost transaction. Transaction processor 1105 then commitsstore data of the one or more instructions to memory as part ofcommitting store data of the coalesced first outermost transaction andsecond outermost transaction to memory.

Instruction identifier 1120 is a hardware structure configured toidentify one or more instructions that follow a first outermosttransaction and precede a second outermost transaction. Instructionidentifier 1120 also determines whether the one or more instructions canbe processed as part of the coalesced transactions based on at least oneof: a time period required to process the one or more instructions, aquantity of resources required to process the one or more instructions,and a category to which the one or more instructions belong.

Footprint handler 1125 is a hardware structure configured to add one ormore markers to a memory footprint of a coalesced first outermosttransaction and a second outermost transaction to indicate respectiveregions of memory that are used for the processing of the firstoutermost transaction and the second outermost transaction. The memoryfootprint includes memory addresses that are read from and written toduring the processing of the first outermost transaction and the secondoutermost transaction, and wherein said markers are used to (i) rollbackthe coalesced transaction in the case of an abort, and (ii) controlcoalescing of outermost transactions.

Coalescing instruction handler 1130 is a hardware structure configuredto execute one or more coalescing instructions for controllingcoalescing of a plurality of outermost transactions. The one or morecoalescing instructions, when executed, indicate to coalescingdeterminer 1110 which outermost transactions can be coalesced. The oneor more coalescing instructions can include one or both of a coalescingprefix that is associated with a transaction begin instruction of anoutermost transaction and a coalescing argument associated with atransaction begin instruction of an outermost transaction. The one ormore coalescing instructions can include one or both of a coalescingprefix that is associated with a transaction end instruction of anoutermost transaction and a coalescing argument associated with thetransaction end instruction of an outermost transaction.

Mode setter 1135 is a hardware structure configured to executeset-transaction-coalesce-mode (STCM) instructions andreset-transaction-coalesce-mode (RTCM) instructions. Executing the STCMinstruction causes the processor to enter STCM mode. Entering STCM modeindicates at least one of (i) that subsequent coalescing instructionsare enabled to cause transactions to-be coalesced, (ii) a maximum numberof instructions that can be present between two outermost transactionsto be coalesced, and (iii) a type of instructions that can be presentbetween two outermost transactions to be coalesced. Conversely,executing a RTCM instruction causes the processor to exit STCM mode.Exiting STCM mode results in one or more of (i) a cessation of executionof subsequent coalescing instructions, (ii) a modification of a numberof instructions that exists between two outermost transactions, and(iii) a modification of a type of instruction that exists between twooutermost transactions.

Coalescing controller 1140 is a hardware structure configured to disablecoalescing of a given outermost transaction based on a determination, bycoalescing determiner 1110, that coalescing will exceed or haspreviously exceeded a threshold value, generated by threshold setter1111. Wherein an exceeding of the threshold value indicates any one of:a stall being exhibited by an outermost transaction to be coalesced, amaximum number of instructions that can exist between two outermosttransactions to be coalesced, a maximum time period required to processoutermost transactions that are coalesced, a quantity of resources thatare required to process outermost transactions that are coalesced, amaximum number of outermost transactions that can be coalesced, a numberof allowable instances of coalescing that particular outermosttransaction that lead to an abort status, and a history of coalescedtransactions that previously experienced an abort.

Run-time monitor 1145 is a hardware structure configured to execute arun-time instrumentation program for monitoring and modifying anassociated program having a plurality of transactions. Based on theexecution of transactions of the associated program, the run-timeinstrumentation program dynamically obtains instrumentation informationassociated with the execution of the associated program. Run-timemonitor 1145 also generates an environment for run-time profiling of thecontinued execution of the associated program to obtain instrumentationinformation. Run-time monitor 1145 profiles the execution of theassociated program using the obtained instrumentation information aswell as changes in the run-time environment of the associated program.Run-time monitor 1145 processes run-time instrumentation directives ofthe run-time instrumentation program and configures the controls ofrun-time instruments based, at least in part, on the processed run-timeinstrumentation directives. The run-time instruments include one or moreinstructions to obtain instrumentation information regarding theexecution of transactions of the associated program. The gatheredinstrumentation information includes one or more of: (i) a reason for acoalesced outermost transaction being aborted, and the number of abortsit has received (ii) a number of instructions between two coalescedoutermost transactions, (iii) a type of instruction between twocoalesced outermost transactions, (iv) whether any of the instructionsbetween two coalesced outermost transactions are restricted from runningin a given outermost transaction, (v) a number of dynamic instructionsin a given outermost transaction, and (vi) the size of a footprint of adynamic instruction in a given outermost transaction.

Transaction execution optimizer 1150 is a hardware structure configuredto, based on obtained instrumentation information, dynamically modifythe continued execution of transactions of the associated program tooptimize transactional execution (TX). The run-time instrumentationprogram modifies the continued execution of the associated program byadding one or more coalescing instructions to the associated program tocontrol coalescing of one or more of the plurality of transactionsbased, at least in part, on an analysis of gathered instrumentationinformation. The one or more coalescing instructions include one or moreof: (i) an instruction to coalesce outermost transactions, (ii) aninstruction to remove a transaction begin or end instruction or to notexecute a transaction begin or end instruction, (iii) an instruction tomodify a transaction begin or end instruction such that the associatedoutermost transaction can-not be coalesced with a type of outermosttransaction if a number of already coalesced instructions is greaterthan a threshold, (iv) an instruction to indicate that a particularoutermost transaction is not-to-be coalesced with a type of outermosttransaction if the number of already coalesced instructions is greaterthan the threshold, (v) an instruction to process non-transactionalinstructions as transactional instructions, (vi) an instruction to ceasecoalescing outermost transactions, and (vii) an instruction to specify amaximum allowable number of coalesced outermost transactions.

Transaction abort determiner 1155 is a hardware structure configured todetermine whether a first plurality of outermost transactions, from theassociated program, which were coalesced, experienced an abort. Thefirst plurality of outermost transactions includes a first instance of afirst transaction.

History updater 1160 is a hardware structure configured to updating, bythe processor, a history of the associated program to reflect theresults of the determination. Based on transaction abort determiner 1155determining that the first plurality of outermost transactions did ordid-not experience an abort, updating the history of the associatedprogram, using history updater 1160, to indicate whether the firstplurality of outermost transactions did or did-not experience an abort.

Transaction flagger 1165 is a hardware structure configured to, based ontransaction abort determiner 1155 determining that the plurality ofoutermost transactions did-not experience an abort, flag the firstoutermost transaction to reflect the determination that the plurality ofoutermost transactions did-not experience an abort. Based on thedetermination that the first plurality of outermost transactions didexperience an abort, flagging, by transaction flagger 1165, the firstoutermost transaction based, at least in part, on the cause of theabort.

Instruction adder 1170 is a hardware structure configured to determinewhether to add instructions to coalesce a second instance of a firstoutermost transaction based, at least in part, on the updated history ofan associated program that included the first instance of the firstoutermost transaction. Based on the determination indicating thatinstructions to coalesce the second instance of the first outermosttransaction are to-be added, instruction adder 1170 causing theexecution of an associated program which adds to a second plurality ofoutermost transactions one or more instructions to coalesce the secondinstance of the first outermost transaction.

Coalescing predictor 1175 is a hardware structure configured to predicta result of coalescing an outermost transaction, at least in part, onthe updated history of the associated program. Such a prediction may bebased on the results of previous instances of transactions beingcoalesced. Such predictions may also be based on similarities betweenvarious transactions.

History 1180 is a hardware structure configured to store and communicatedata that can be used to predict the outcome of coalescing outermosttransactions. Such data may include the updated history of associatedprograms and results of previous instances of transactions beingcoalesced. Such data may be used by coalescing predictor 1175 to predictthe result of coalescing an outermost transaction. The data included inhistory 1180 can be updated by, for example, hardware structures such ashistory updater 1160.

FIG. 12 depicts an example of transaction nesting in an embodiment. FIG.12 is intended to aid the reader in the identifying the differencesbetween nested transactions and coalescing outermost transactions. Anexample of nested transactions are the transactions within 1206. Eachtime a TBEGIN is encountered, the nesting depth in incremented by 1 andeach time a TEND is encountered the nesting depth is decremented by 1.An outermost TBEGIN is the one that increments the depth from 0 to 1 andan outermost TEND is the one that decrements the depth from 1 to 0.

Known art solutions are directed to the handling of nested transactions.Conversely, the solutions described in FIGS. 4-8 address the coalescingof outermost transactions. In FIG. 9, this can be understood to be thecombining of outermost transaction TB1-TE1 in 1206 with outermosttransaction TB1-TE1 in 1208. The instructions can be executed in orderbased on the program instruction order 1202 (i.e., the order in whichthe program issues the instructions) per thread. For each transactionbegin (TBEGIN) instruction 1210, the nesting depth 1204 (i) is increasedby one. For each transaction end (TEND) instruction 1212, the nestingdepth 1204 decreases by one. When a first outer transaction 1206 isstarted, outermost transaction count (j) is increased by one. When asecond outer transaction 1208 is started, j is increased by one. As eachof the first outer transaction 1206 and the second outer transaction1208 are completed j is decremented by 1.

In an embodiment, historical data is accumulated for each transactionand saved with an identifier of the transaction. The identifier of thetransaction might be the instruction address of the BEGIN instructionthat starts a transaction, an ID associated with the Begin instruction,provided by the programmer, or a program specific recording of anidentifier, such as a store instruction preceding the transaction forstoring an identifier of the transaction that is about to begin.Information in the historical data may include a count of aborts of thetransaction, a count of interrupts of the transaction, a count ofcompletions of the transaction, an indicator identifying transactionscoalesced with the transaction, and other instrumentation data.

In an embodiment, a dynamic optimizer may combine multiple transactionsduring code optimization and code generation. For example, the optimizermay be part of a Java just in time (JIT) compiler. In anotherembodiment, the optimizer may be part of a dynamic code optimizer (DCO)component. In yet another embodiment, the optimizer may be part of abinary translator (BT) translating from one instruction set architecture(ISA) to another ISA. In another embodiment components of a dynamicoptimizer may be part of a static compiler.

In one embodiment, the optimizer may start without combining(coalescing) transactions. Execution profile data are collected, fortransactions, by way of program instrumentation (e.g., in someembodiments using either software counters tracking transaction abortsfor each transaction and of transaction-associated overheads or ahardware runtime instrumentation or performance monitoring unit) arecollected. In this embodiment, instructions of multiple subsequenttransactions and all intervening instructions (coalesces transactions)may be coalesced during a subsequent code reoptimization pass ifprevious instances of the transactions are determined to have highsuccessful completion rates based on the execution profiles collected.In one embodiment, after transaction coalescing, profiles continue to becollected. In such an embodiment, in a later code re-optimization phase,if the combined transactions show an undesirably low success rate, afurther re-optimization can then un-combine the transactions such thatfuture instances of the transactions are executed individually. Inanother embodiment, the optimizer may start by aggressively coalescingtransactions, collect execution profiles and uncombine transactions whenprevious instances of the combined transactions show an undesirably lowsuccess rate based on execution profiles. In at least one suchembodiment, initial combining of transactions is based on heuritstics.In one or more embodiment, execution profiles and heuristics are used inconjunction with a cost model, to determine whether an increase inexecution time due to failure rates of large coalesced instructionsexceeds the reduction in the overhead of starting and endingtransactions.

In one embodiment, profiles may be collected using a performancemeasurement utility (PMU) or runtime instrumentation facility. Inanother embodiment, statistics may be generated by statistics-collectinginstructions inserted into the code (i.e., instrumenting the code). Inyet another embodiment, instruction statistics may be obtained byperiodic sampling. In yet another embodiment, instruction statistics maybe obtained by an initial interpretation.

In one embodiment, the optimizer may continue to dynamically optimizeresponding to dynamic profiles. In other embodiments, hysteresis may beimplemented, to prevent constant re-optimization, e.g., such that whenan optimization has performed, reoptimization must be triggered by asignificant deviation from the previously observed behavior, accordingto a cost function. In yet another embodiment, re-optimization may bestopped after an initial optimization and optionally after a number ‘n’re-optimization steps. In yet another embodiment, re-optimization may bedeferred after an initial re-optimization for a time constant ‘t’ periodof time. In at least one embodiment, the time constant T may increasewith each optimization step i, (e.g., t=i*const or t=const ̂i).

Thus in one exemplary software embodiment of the present transactioncoalescing invention, a code fragment having multiple transactionsgenerated from multiple atomic tasks such as:

instructions A

TBEGIN

instructions B

TEND

instructions C

TBEGIN

instructions D

TEND

instructions E

The code fragment shown above might, for example be converted into analternate code sequence corresponding to a single transaction handlingmultiple atomic tasks:

instructions A

TBEGIN

instructions Binstructions Cinstructions D

TEND

instructions E

In an embodiment, 1300 of FIG. 13 demonstrates a software implementationof a transaction coalescing method (when, for example, no specialhardware support for hardware-controlled transaction coalescing isprovided). In accordance with a software coalescing method, in oneembodiment, a dynamic code generation algorithm combines instructions ofmultiple transactions, and any intervening instructions into singletransactions. In another embodiment, an intermediate representationgenerator 900 (in one example operating on Java byte code) may indicateatomic tasks to be performed and a dynamic optimizer 920 and codegenerator 930 may determine whether atomic tasks can be combined into acoalesced transactions or that the atomic tasks must be implemented incorresponding single transactions. In one embodiment, the method 1300 isexecuted as part of the code generation 930 of machine code in arun-time environment. In one embodiment, runtime information iscollected. When runtime information indicates that multiple transactionscan profitably merged, because of the overhead incurred for starting andending individual transactions, the profiling logic may indicate to thecode generator 930, that the transaction is to be coalesced. In at leastone embodiment, the decision to coalesce multiple transactions mayfurther includes resource usage models and a determination whether abortrates of individual transactions allow profitable transaction merging,since the penalty for transaction aborts increases as transactions aremerged. In one embodiment, the resource models include information aboutthe average transaction footprint, i.e., the number of read and writesets tracked, and the resource model determines whether one or morecoalesced transactions may still be tracked by the available hardwareresources of a specific processor.

When transactions have been coalesced, profiling logic may gatherinformation about transaction aborts of previous instances of thetransaction. If the abort rate of transaction aborts of coalescedinstructions exceeds a threshold, transactions may be marked for thecode generator 930 to be not coalesced when the code generatorre-optimizes the present transactions. In one embodiment, codegeneration and re-optimization may be initiated after a fixed amount oftime for each code fragment. In another embodiment, code generation maybe re-initiated to start code re-optimization responsive to reaching afixed number of instrumentation data and re-optimization decisions(e.g., to coalesce, or un-coalesce (un-merge) a number of transactions).In yet another embodiment, code generation may be reinitiated responsiveto a cost function, where a cost function may, for example, determinethat the opportunity for performance improvement from re-optimizationexceeds one of a fraction or multiple of code generation cost. Othercost functions are possible, such as a rate of transaction aborts beingexceeded, and so forth.

In one embodiment, runtime information may be obtained from hardwareinstrumentation. In another embodiment, runtime information may beobtained from instructions tangible incorporated into generated code. Inanother embodiment, runtime information may be obtained responsive toperforming heuristic algorithms determining expected runtime behaviorfrom code fragment analysis.

In one embodiment, when a threshold for re-optimization data is reached,the code generator may re-optimize coalescing of a transaction.

In another embodiment, transaction coalescing may be implemented in astatic compiler, i.e., a compiler performing code optimization and codegeneration steps prior to execution, and generating a programexecutable. In one embodiment, transaction coalescing may be based onprogrammer hints, pragmas (the ‘#pragma’ directive is the methodspecified by the C standard for providing additional information to thecompiler), and other programmer provided input (such as, for example,including but not limited to an indication that transactions below acertain programmer-specified transaction size should be coalesced). Inanother embodiment, transactions may be coalesced based on heuristics.In one embodiment, the heuristics are based on a determination thatmultiple transactions are below a heuristic-specified transaction size.In another embodiment, the heuristics may be based on a determinationthat multiple transactions share one or more of multiple transactionread and transaction write sets. In another embodiment, the heuristicsmay be based on a determination that the output of a first transactionis used by a second transaction, and so forth.

In yet another embodiment, the static compiler used profile directedfeedback optimization (and optionally in conjunction with the method ofFIG. 22). In a first compilation pass (and optionally in conjunctionwith the method of FIG. 23), the compiler may generate a program binary(optionally including coalesced transactions which may be based onheuristics and hints) which is instrumented either with softwarecounters or by configuring one of a runtime instrumentation, performancemonitoring or program sampling unit. The program is executed, executionstatistics are collected and stored in a file. In a second compilationpass (and optionally in conjunction with FIG. 24), the compiler mayperform compilation steps in accordance with static compiler methods,further reading stored execution profiles and performing transactioncoalescing method 1300 for those transaction which are candidates fortransaction coalescing, in conjunction with the obtained executionprofiles to generate a program executable containing coalescedtransactions based on the execution profiles. Those skilled in the artwill understand that a second pass binary may or may not beinstrumented, and further execution profiles may be collected from asecond pass binary, reinitiating a second compiler pass with suchenhanced execution profiles.

FIG. 13 illustrates, in another embodiment, a method, 1300, ofoperational activity executed by a dynamic compiler that performsaspects of the transaction coalescing process, in accordance withembodiments of the present disclosure. It should be noted that such adynamic compiler can, in certain embodiments, allow for the coalescingof outermost transactions without the requirement of hardware that hasbeen configured for coalescing of outermost transactions.

In some embodiments, such a dynamic compiler, incorporates variousaspects of coalescing control 300, dynamic prediction 500, controlindicator 600 and coalescing optimizer 700, as well as software aspectsof transaction coalescing operations 400 to allow the dynamic compilerto make determinations and generate instructions as described in thediscussion of method 1300. In other embodiments, coalescing control 300,dynamic prediction 500, control indicator 600 and coalescing optimizer700, as well as aspects of transaction coalescing operations 400 work inconjunction with and are in communication with such a dynamic compiler;thereby allowing the dynamic compiler to execute the operations ofmethod 1300.

In an embodiment 1300 a software implementation of transaction iscoalesced when no hardware support for hardware-controlled transactioncoalescing is provided. In one embodiment, code generation andre-optimization is initiated after a fixed amount of time for each codefragment. A code fragment can be any of a plurality of known regionsthat dynamic optimizers may act upon. In previous code generations,these include: a trace, a tree region, a function, a hot region, etc.,or any other group of instructions a dynamic code optimization and/orcode generation method may be executed upon.

In operation 1310, non-transactional instructions are generated by thedynamic compiler to be executed non-transactionally. In decisionoperation 1320, a determination is made as to whether the end of thecode, of the non-transactional instructions, has been reached, i.e.,whether all instructions of a code fragment have been generated by thedynamic compiler and whether the end of a code fragment has beenreached. If it is determined that the end of the code has been reached(decision operation 1320, yes branch), then method 1300 ends. If it isdetermined that the end of the code has-not been reached (decisionoperation 1320, no branch), then method 1300 proceeds to operation 1330.

In operation 1330, a transaction begin instruction is generated inresponse to the identification of the beginning of a transaction. Inoperation 1340, the transaction instructions are generated. In decisionoperation 1350, a determination is made as to whether coalescing of thetransaction, with a subsequent transaction, is permitted.

If it is determined that coalescing of the transaction is-not permitted(decision operation 1350, no branch), then method 1300 proceeds tooperation 1360. In operation 1360, a transaction end instruction isgenerated in response to the identification of the end of thetransaction. Method 1300 then proceeds to 1310. If it is determined thatcoalescing of the transaction is permitted (decision operation 1350, yesbranch), then method 1300 proceeds to operation 1370.

In operation 1370 non-transactional instructions are generated in theform of transactional instructions. Such instructions follow the firsttransaction, which is to be coalesced, and precede the next transaction.In other words, the non-transactional instructions, between the firstand second transaction to be coalesced, are generated as part of thecoalesced transaction. In at least one embodiment, an analysis todetermine whether coalescing of transactions is permitted includes ananalysis of intervening instructions to assure that all interveninginstructions may be executed transactionally. In an alternativeembodiment, no such determination is made during initial determinationas to whether coalescing of transactions is permitted. In such analternative embodiment, when an instruction that cannot be executedtransactionally is encountered, the transaction is ended by generationof a transaction end instruction, as described in operation 1360, priorto generation of the non-transactional instruction.

In decision operation 1380, of method 1300, it is determined whether thebeginning of the next transaction has been reached. If it is determinedthat the beginning of the next transaction has been reached (decisionoperation 1380, yes branch), then method 1300 proceeds to operation1340. If it is determined that the beginning of the next transactionhas-not been reached (decision operation 1380, no branch), then method1300 proceeds to operation 1370.

While the transaction coalescing method has been described inconjunction with including intervening instructions between a first anda second transaction, in at least one embodiment, instruction schedulingmay be performed such as to perform at least one intervening instructionbetween a first and a second transaction being coalesced either beforeor after the coalesced transaction.

Various embodiments of the present disclosure may be implemented in adata processing system suitable for storing and/or executing programcode that includes at least one processor coupled directly or indirectlyto memory elements through a system bus. The memory elements include,for instance, local memory employed during actual execution of theprogram code, bulk storage, and cache memory which provide temporarystorage of at least some program code in order to reduce the number oftimes code must be retrieved from bulk storage during execution.

FIG. 14 illustrates an embodiment, 1400, of the present disclosure forpredicting the outcome of coalescing outermost memory transactions.

The embodiment executing 1410, by a processor, a run-timeinstrumentation program for monitoring and modifying an associatedprogram having a plurality of transactions. The embodiment initiating1420, by the processor, execution of the associated program. Theembodiment based on execution of transactions, by the processor, of theassociated program, the run-time instrumentation program dynamicallyobtaining 1430 instrumentation information associated with theexecution. The embodiment based on the obtained instrumentationinformation, dynamically modifying 1440 continued execution oftransactions of the associated program to optimize transactionalexecution (TX).

As depicted in FIG. 15, included as part of embodiment 1400, theembodiment determining 1510 by the instrumentation program, that a firstoutermost transaction and a second outermost transaction of theplurality of transactions of the associated program should be coalesced.The embodiment coalescing 1520 transactions based on the determining1510.

As depicted in FIG. 16, as part of executing 1410, an embodiment,generating 1610, by the processor, an environment for run-time profilingof the continued execution of the associated program for obtaininginstrumentation information. The embodiment profiling 1620, by theprocessor, the execution of the associated program using obtainedinstrumentation information and changes in a run-time environment of theassociated program.

As depicted in FIG. 17, as part of executing 1410, an embodimentprocessing 1710, by the processor, a run-time instrumentation directiveof the run-time instrumentation program. The embodiment configuring1720, by the processor, a control of a run-time instrument based, atleast in part, on the processed run-time instrumentation directive,wherein the run-time instrument includes one or more instructions toobtain instrumentation information regarding the execution oftransactions of the associated program.

As depicted in FIG. 18, included as part of dynamically modifying 1440,in an embodiment, the run-time instrumentation program modifying 1800the continued execution of the associated program includes adding one ormore coalescing instructions to the associated program to controlcoalescing of one or more of the plurality of transactions based, atleast in part, on an analysis of gathered instrumentation information.

As depicted in FIG. 19, in an embodiment, the one or more coalescinginstructions include one or more of: (i) an instruction to coalesceoutermost transactions, (ii) an instruction to remove a transactionbegin or end instruction or to not execute a transaction begin or endinstruction, (iii) an instruction to modify a transaction begin or endinstruction such that the associated outermost transaction can-not becoalesced with a type of outermost transaction if a number of alreadycoalesced instructions is greater than a threshold, (iv) an instructionto indicate that a particular outermost transaction is not-to-becoalesced with a type of outermost transaction if the number of alreadycoalesced instructions is greater than the threshold, (v) an instructionto process non-transactional instructions as transactional instructions,(vi) an instruction to cease coalescing outermost transactions, and(vii) an instruction to specify a maximum allowable number of coalescedoutermost transactions.

As depicted in FIG. 20, in profiling 1620, in an embodiment, theobtained instrumentation information includes one or more of: (i) areason for a coalesced outermost transaction being aborted, and thenumber of aborts it has received, (ii) a number of instructions betweentwo coalesced outermost transactions, (iii) a type of instructionbetween two coalesced outermost transactions, (iv) whether any of theinstructions between two coalesced outermost transactions are restrictedfrom running in a given outermost transaction, (v) a number of dynamicinstructions in a given outermost transaction, and (vi) the size of afootprint of a dynamic instruction in a given outermost transaction.

In an embodiment of a compiler or JIT compiler implementation, referringto FIG. 7, rather than inserting coalescing instructions 620,instruction coalescing is performed to obtain instrumentation data.

Referring to FIG. 21, an example method 2100 for determining whether tomerge transactions is shown. Program characteristics are accessed 2101using any of heuristics, programmer hints and instrumentation data.

Then, a determination is made 2102 as to whether two transactions shouldbe merged (coalesced) based on metrics including the programcharacteristics.

If 2103 merge is warranted, a coalesced transaction encompassing arequirement for multiple atomic operations is generated. Otherwise 2104individual transactions are generated for each atomic operationrequirement.

Referring to FIG. 22, an example embodiment of the method is shown. Afirst pass run of a compiler 2300 is made and the resulting machinecode, program 1, is executed 2202. Statistics gathered from executingthe program 1 2202 and stored 2203 in a statistics memory 2204.Subsequently, the compiler is run again as a second pass 2400 and theresulting machine instructions generated as program 2 are executed 2206.If 2208 more statics are gathered, they are merged 2209 with previousstatistics and stored in statistics memory 2204, otherwise, thecompilation is done.

Referring to FIG. 23, an example Pass 1 compilation 2300 is shown. Thesource program (source code) is read 2301 and a determination 2303 ismade based on programmer hints for example as to whether an atomicoperation is required. An intermediate representation of the program isgenerated 2304 and heuristics are performed 2305. A determination ismade 2100 as to whether atomic operations can be joined in a coalescedtransaction and machine code is generated 2105 2104. The pass 1 compilerinserts code 2306 to gather instrumentation data and after the code isgenerated 2307, the machine code is written 2308 to an object file forexecution.

FIG. 24 depicts an example Pass 2 compiler 2400. The source program(source code) is read 2301 and a determination 2303 is made based onprogrammer hints for example as to whether an atomic operation isrequired. Instrumentation data is read 2403 and an intermediaterepresentation of the program is generated 2401 and heuristics areperformed 2305. Based on one or more of instrumentation data, programmerhints and heuristics, a determination is made 2100 as to whether atomicoperations can be joined in a coalesced transaction and machine code isgenerated 2105 2104. The pass 2 compiler inserts code 2306 to gatherinstrumentation data and after the code is generated 2307, the machinecode is written 2308 to an object file for execution.

Referring to FIG. 25, in an embodiment controlling a coalescing ofoutermost memory transactions is performed in process 2501, thecoalescing causing committing of memory store data to memory for a firsttransaction to be done at transaction execution (TX) end of a secondtransaction, wherein optimized machine instructions are generated basedon an intermediate representation of a program.

In an embodiment, based on the intermediate representation, a processorgenerates 2502 a first module of optimized non-transactional machineinstructions, and based on the intermediate representation identifyingtwo atomic tasks to be performed, the two atomic tasks consisting of afirst atomic task and a second atomic task, a determination is made 2503whether the two atomic tasks are to be coalesced 2504 into a singleatomic task, and based on determining that the two atomic tasks are notto be coalesced, a first transaction of transactional machineinstructions to be executed is generated for the first atomic task and asecond transaction of transactional machine instructions to be executedis generated for the second atomic task; and based on determining thatthe two atomic tasks are to be coalesced 2505 a single coalescedtransaction of transactional machine instructions to be executed isgenerated for the two atomic tasks.

In an embodiment, generation 2601 of optimized machine instructions isperformed by a just-in-time (JIT) compiler.

In an embodiment a run-time instrumentation program is executed 2602 ona previous instance of a previous transaction comprising of any one ofsaid single coalesced transaction, said first transaction and saidsecond transaction to determine whether the two atomic tasks are to becoalesced.

In an embodiment, executing the run-time instrumentation program 2603includes: generating 2604 an environment for run-time profiling of theprevious instance of the previous transaction for obtaininginstrumentation information; and profiling 2605 the execution of theprevious instance of the previous transaction using obtainedinstrumentation information; and based on the profiling, changing 2606run-time environment of the program.

Referring to FIG. 27, in an embodiment, a run-time instrumentationdirective of the run-time instrumentation program is processed 2701; anda control of a run-time instrument is configured 2702 based, at least inpart, on the processed run-time instrumentation directive, wherein therun-time instrumentation program includes one or more instructions toobtain instrumentation information regarding the execution oftransactions of the program.

In an embodiment the run-time instrumentation program modifies 2703continued execution of the program, the modifying including adding oneor more coalescing instructions to the associated program to controlcoalescing of transactions based, at least in part, on an analysis ofgathered instrumentation information.

Referring to FIG. 28, in an embodiment, the one or more coalescinginstructions include 2801 one or more of: (i) an instruction to coalesceoutermost transactions, (ii) an instruction to remove a transactionbegin or end instruction or to not execute a transaction begin or endinstruction, (iii) an instruction to modify a transaction begin or endinstruction such that an associated outermost transaction can-not becoalesced with a type of outermost transaction if a number of alreadycoalesced instructions is greater than a threshold, (iv) an instructionto indicate that a particular outermost transaction is not-to-becoalesced with a type of outermost transaction if the number of alreadycoalesced instructions is greater than the threshold, (v) an instructionto process non-transactional instructions as transactional instructions,(vi) an instruction to cease coalescing outermost transactions, and(vii) an instruction to specify a maximum allowable number of coalescedoutermost transactions wherein a run-time instrumentation program isexecuted 2902 on a previous instance of a previous transactioncomprising of any one of said single coalesced transaction, said firsttransaction and said second transaction to determine whether the twoatomic tasks are to be coalesced.

Referring to FIG. 29, in an embodiment, the determining whether the twoatomic tasks are to be coalesced is based on 2901 one or more of: (i) areason for a coalesced outermost transaction being aborted, and a numberof aborts it has received, (ii) a number of instructions between twocoalesced outermost transactions, (iii) a type of instruction betweentwo coalesced outermost transactions, (iv) whether any of theinstructions between two coalesced outermost transactions are restrictedfrom running in a given outermost transaction, (v) a number of dynamicinstructions in a given outermost transaction, and (vi) a size of afootprint of a dynamic instruction in a given outermost transaction.

Input/Output or I/O devices (including, but not limited to, keyboards,displays, pointing devices, DASD, tape, CDs, DVDs, thumb drives andother memory media, etc.) can be coupled to the system either directlyor through intervening I/O controllers. Network adapters may also becoupled to the system to enable the data processing system to becomecoupled to other data processing systems or remote printers or storagedevices through intervening private or public networks. Modems, cablemodems, and Ethernet cards are just a few of the available types ofnetwork adapters.

One or more of the capabilities of the present disclosure can beimplemented in software, firmware, hardware, or some combinationthereof. Further, one or more of the capabilities can be emulated.

One or more aspects of the present disclosure can be included in anarticle of manufacture (e.g., one or more computer program products)having, for instance, computer readable storage media 1008 of FIG. 10.The media has embodied therein, for instance, computer readable programcode (instructions) to provide and facilitate the capabilities of thepresent invention. The article of manufacture can be included as a partof a computer system or as a separate product.

An embodiment may be a computer program product for enabling processorcircuits to perform elements of the disclosure, the computer programproduct comprising a computer readable storage medium readable by aprocessing circuit and storing instructions for execution by theprocessing circuit for performing a method.

The computer readable storage medium (or media), being a tangible,non-transitory, storage medium having instructions recorded thereon forcausing a processor circuit to perform a method. The “computer readablestorage medium” being non-transitory at least because once theinstructions are recorded on the medium, the recorded instructions canbe subsequently read one or more times by the processor circuit at atimes that are independent of the time of recording. The “computerreadable storage media” being non-transitory including devices thatretain recorded information only while powered (volatile devices) anddevices that retain recorded information independently of being powered(non-volatile devices). An example, non-exhaustive list of“non-transitory storage media” includes, but is not limited to, forexample:

-   -   a semi-conductor storage device comprising, for example, a        memory array such as a RAM or a memory circuit such as latch        having instructions recorded thereon;    -   a mechanically encoded device such as punch-cards or raised        structures in a groove having instructions recorded thereon;    -   an optically readable device such as a CD or DVD having        instructions recorded thereon; and    -   a magnetic encoded device such as a magnetic tape or a magnetic        disk having instructions recorded thereon.

A non-exhaustive list of examples of computer readable storage mediuminclude the following: a portable computer diskette, a hard disk, arandom access memory (RAM), a read-only memory (ROM), an erasableprogrammable read-only memory (EPROM or Flash memory), a portablecompact disc read-only memory (CD-ROM).

Although one or more examples have been provided herein, these are onlyexamples. Many variations are possible without departing from the spiritof the present embodiment. For instance, processing environments otherthan the examples provided herein may include and/or benefit from one ormore aspects of the present embodiment. Further, the environment neednot be based on the z/Architecture®, but instead can be based on otherarchitectures offered by, for instance, IBM®, Intel®, Sun Microsystems,as well as others. Yet further, the environment can include multipleprocessors, be partitioned, and/or be coupled to other systems, asexamples.

As used herein, the term “obtaining” includes, but is not limited to,fetching, receiving, having, providing, being provided, creating,developing, etc.

The capabilities of one or more aspects of the present disclosure can beimplemented in software, firmware, hardware, or some combinationthereof. At least one program storage device readable by a machineembodying at least one program of instructions executable by the machineto perform the capabilities of the present disclosure can be provided.

The flow diagrams depicted herein are just examples. There may be manyvariations to these diagrams or the steps (or operations) describedtherein without departing from the spirit of the disclosure. Forinstance, the steps may be performed in a differing order, or steps maybe added, deleted, or modified. All of these variations are considered apart of the claimed disclosure.

Although preferred embodiments have been depicted and described indetail herein, it will be apparent to those skilled in the relevant artthat various modifications, additions, substitutions and the like can bemade without departing from the spirit of the disclosure, and these are,therefore, considered to be within the scope of the disclosure, asdefined in the following claims.

What is claimed is:
 1. A method of controlling a coalescing of outermost memory transactions, the coalescing causing committing of memory store data to memory for a first transaction to be done at transaction execution (TX) end of a second transaction, the method for generating optimized machine instructions based on an intermediate representation of a program, the method comprising: based on the intermediate representation, generating, by a processor, a first module of optimized non-transactional machine instructions; based on the intermediate representation identifying two atomic tasks to be performed, the two atomic tasks consisting of a first atomic task and a second atomic task, determining whether the two atomic tasks are to be coalesced into a single atomic task; based on determining that the two atomic tasks are not to be coalesced, generating for the first atomic task, a first transaction of transactional machine instructions to be executed and generating for the second atomic task, a second transaction of transactional machine instructions to be executed; and based on determining that the two atomic tasks are to be coalesced, generating for the two atomic tasks, a single coalesced transaction of transactional machine instructions to be executed.
 2. The method according to claim 1, wherein the method for generating optimized machine instructions is performed by a just-in-time (JIT) compiler.
 3. The method according to claim 1, further comprising: executing a run-time instrumentation program on a previous instance of a previous transaction comprising of any one of said single coalesced transaction, said first transaction and said second transaction to determine whether the two atomic tasks are to be coalesced.
 4. The method of claim 3, wherein executing the run-time instrumentation program includes: generating an environment for run-time profiling of the previous instance of the previous transaction for obtaining instrumentation information; and profiling the execution of the previous instance of the previous transaction using obtained instrumentation information; and based on the profiling, changing run-time environment of the program.
 5. The method of claim 4, the method further comprising: processing a run-time instrumentation directive of the run-time instrumentation program; and configuring a control of a run-time instrument based, at least in part, on the processed run-time instrumentation directive, wherein the run-time instrumentation program includes one or more instructions to obtain instrumentation information regarding the execution of transactions of the program.
 6. The method of claim 3, wherein the run-time instrumentation program modifies continued execution of the program, the modifying including adding one or more coalescing instructions to the associated program to control coalescing of transactions based, at least in part, on an analysis of gathered instrumentation information.
 7. The method of claim 5, wherein the one or more coalescing instructions include one or more of: (i) an instruction to coalesce outermost transactions, (ii) an instruction to remove a transaction begin or end instruction or to not execute a transaction begin or end instruction, (iii) an instruction to modify a transaction begin or end instruction such that an associated outermost transaction can-not be coalesced with a type of outermost transaction if a number of already coalesced instructions is greater than a threshold, (iv) an instruction to indicate that a particular outermost transaction is not-to-be coalesced with a type of outermost transaction if the number of already coalesced instructions is greater than the threshold, (v) an instruction to process non-transactional instructions as transactional instructions, (vi) an instruction to cease coalescing outermost transactions, and (vii) an instruction to specify a maximum allowable number of coalesced outermost transactions, the method further comprising: executing a run-time instrumentation program on a previous instance of a previous transaction including one or more of said single coalesced transaction, said first transaction and said second transaction to determine whether the two atomic tasks are to be coalesced.
 8. The method of claim 3, wherein the determining whether the two atomic tasks are to be coalesced is based on one or more of: (i) a reason for a coalesced outermost transaction being aborted, and a number of aborts it has received, (ii) a number of instructions between two coalesced outermost transactions, (iii) a type of instruction between two coalesced outermost transactions, (iv) whether any of the instructions between two coalesced outermost transactions are restricted from running in a given outermost transaction, (v) a number of dynamic instructions in a given outermost transaction, and (vi) a size of a footprint of a dynamic instruction in a given outermost transaction. 